Managing Android Activity stack: bring specific activity instance to front

戏子无情 提交于 2019-12-13 05:05:00

问题


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

  • TextChatActivity - a conversation. Can have multiple instances for multiple conversations.
  • ConvListActivity - a list of all the 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.

  • Let's say I have 2 open conversations (TextChatActivity) A and B, and B is on front.
  • Now I got a notification that leads to conversation A. I want it to bring conversation A TextChatActivity to front.

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

Thanks!


回答1:


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.




回答2:


Just start an activity and set the flag FLAG_ACTIVITY_CLEAR_TOP



来源:https://stackoverflow.com/questions/17008176/managing-android-activity-stack-bring-specific-activity-instance-to-front

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!