How to bring an activity to foreground (top of sta

2019-01-02 17:31发布

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?

9条回答
谁念西风独自凉
2楼-- · 2019-01-02 18:05

You can try this FLAG_ACTIVITY_REORDER_TO_FRONT (the document describes exactly what you want to)

查看更多
春风洒进眼中
3楼-- · 2019-01-02 18:06

I think a combination of Intent flags should do the trick. In particular, Intent.FLAG_ACTIVITY_CLEAR_TOP and Intent.FLAG_ACTIVITY_NEW_TASK.

Add these flags to your intent before calling startActvity.

查看更多
妖精总统
4楼-- · 2019-01-02 18:08

Here is a code-example of how you can do it:

Intent intent = getIntent(getApplicationContext(), A.class)

This will make sure that you only have one instance of an activity on the stack.

private static Intent getIntent(Context context, Class<?> cls) {
    Intent intent = new Intent(context, cls);
    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    return intent;
}
查看更多
零度萤火
5楼-- · 2019-01-02 18:10

i.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);

Note Your homeactivity launchmode should be single_task

查看更多
听够珍惜
6楼-- · 2019-01-02 18:18

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:

Intent i = new Intent(this, MyMainActivity.class);
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(i);

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.

查看更多
牵手、夕阳
7楼-- · 2019-01-02 18:21

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:

  1. Notification triggers a broadcast action with an extra the name of the activity to launch.

  2. 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

  3. Activity is brought to the top of activity stack, no duplicates.

查看更多
登录 后发表回答