简体   繁体   中英

How to launch activity the same way launchers do?

I have an Activity A which is declared as singleTop and android.intent.action.MAIN in Android Manifest. I start it from launcher, then launch another activity B through Intent and then press Home button. Now I have a task with activity stack " A , B " waiting in background. If I then again start activity A from launcher I get back already running instance with a stack restored (activity B running in foreground).

This is nice. And I want to achieve the same effect when launching activity A from my own Notification . I've tried different combinations of Intent flags but I've got either a new instance of activity A or the same instance but with cleared stack (no activity B in foreground).

First of all, let's make sure that the system won't kill your Activity B when you are not using that task for a long time.

If the user leaves a task for a long time, the system clears the task of all activities except the root activity. When the user returns to the task again, only the root activity is restored. The system behaves this way, because, after an extended amount of time, users likely have abandoned what they were doing before and are returning to the task to begin something new.

There are some activity attributes that you can use to modify this behavior:

alwaysRetainTaskState : If this attribute is set to "true" in the root activity of a task, the default behavior just described does not happen. The task retains all activities in its stack even after a long period. So what you need to do is to set this to true under your <activity> tag in your manifest file for A.

Second, you won't need singleTop . Check this figure from Android docs. I guess this is what you want. If you start an activity that specifies the singleTask launch mode, then if an instance of that activity exists in a background task, that whole task is brought to the foreground. At this point, the back stack now includes all activities from the task brought forward, at the top of the stack.

So you also need to add singleTask under the tag of A and B, instead of singleTop . Then, you need to launch activity A from Notification without any flags but FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_REORDER_TO_FRONT (optional).

I haven't tried this myself but I have a strong belief that it will work. Try it and let me know if it doesn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM