In Android, I defined an activity ExampleActivity.
When my application was launched, an instance of this A-Activity was created, say it is A
.
When user clicked a button in A
, another instance of B-Activity, B was created. Now the task stack is B-A, with B at the top. Then, user clicked a button on B, another instance of C-Activity, and C was created. Now the task stack is C-B-A, with C at the top.
Now, when user click a button on C, I want the application to bring A to the foreground, i.e. make A to be at the top of task stack, A-C-B.
How can I write the code to make it happen?
You can try this
FLAG_ACTIVITY_REORDER_TO_FRONT
(the document describes exactly what you want to)I think a combination of
Intent
flags should do the trick. In particular,Intent.FLAG_ACTIVITY_CLEAR_TOP
andIntent.FLAG_ACTIVITY_NEW_TASK
.Add these flags to your intent before calling
startActvity
.Here is a code-example of how you can do it:
This will make sure that you only have one instance of an activity on the stack.
i.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
Note Your homeactivity launchmode should be single_task
The best way I found to do this was to use the same intent as the Android home screen uses - the app Launcher.
For example:
This way, whatever activity in my package was most recently used by the user is brought back to the front again. I found this useful in using my service's PendingIntent to get the user back to my app.
If you want to bring an activity to the top of the stack when clicking on a Notification then you may need to do the following to make the FLAG_ACTIVITY_REORDER_TO_FRONT work:
The solution for me for this was to make a broadcast receiver that listens to broadcast actions that the notification triggers. So basically:
Notification triggers a broadcast action with an extra the name of the activity to launch.
Broadcast receiver catches this when the notification is clicked, then creates an intent to launch that activity using the FLAG_ACTIVITY_REORDER_TO_FRONT flag
Activity is brought to the top of activity stack, no duplicates.