Taldroid
Taldroid

Reputation: 380

Managing Android Activity stack: bring specific activity instance to front

I have a text message app which has two main activities:

In addition, a TextChatActivity of a certain conversation can be opened via a status bar notification.

What I want to do is to bring a specific TextChatActivity instance to the front.

How can I do that without opening a new instance of TextChatActivity for conversation A?

Thanks!

Upvotes: 0

Views: 842

Answers (2)

David Wasser
David Wasser

Reputation: 95578

Actually, you can't. If you have multiple instances of an activity in the stack, there is no way to address a unique instance of an activity so that you could bring it to the front.

Your architecture is not good. Because of the way Android works, you would be better off if you had a single instance of this activity, and allow the user to switch between conversations, not by creating a new instance of an activity, but just by switching out the underlying data for the existing activity. In this way, you only ever have one instance of the activity and you can simply change the data that you are displaying.

In your "notification" example, the Intent that you start from the notification should have an "extra" that indicates which conversation the user wants to show. You should ensure that there is only one instance of your TextChatActivity by declaring it with launchMode="singleTop" or by setting FLAG_ACTIVITY_SINGLE_TOP when you start it. When onNewIntent() is called in your activity, check the "extras" and adjust the content to show the desired conversation.

If you want to create the "illusion" of an activity per conversation, then you can override `onBackPressed() and manage your own "stack" of conversations in the activity, so that when a user presses the BACK key, you can go back in the "stack" of conversations and show him the previous one, just by modifying the data that is displayed.

Upvotes: 1

handrenliang
handrenliang

Reputation: 1047

Just start an activity and set the flag FLAG_ACTIVITY_CLEAR_TOP

Upvotes: 0

Related Questions