Android: Clear the back stack

2018-12-31 09:47发布

In Android I have some activities, let's say A, B, C.

In A I use this code to open B:

Intent intent = new Intent(this, B.class);
startActivity(intent);

In B I use this code to open C:

Intent intent = new Intent(this, C.class);
startActivity(intent);

When the user taps a button in C I want to go back to A and clear the back stack (close both B and C). So when the user use the back button B and C will not show up, I've been trying the following:

Intent intent = new Intent(this, A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
startActivity(intent);

But B and C are still showing up if I use the back button when I'm back in activity A. How can I avoid this?

30条回答
与风俱净
2楼-- · 2018-12-31 10:16

I found an interesting solution which might help. I did this in my onBackPressed() method.

finishAffinity();
finish();

FinishAffinity removes the connection of the existing activity to its stack. And then finish helps you exit that activity. Which will eventually exit the application.

查看更多
看风景的人
3楼-- · 2018-12-31 10:16
Intent intent = new Intent(this, A.class);
startActivity(intent);
finish();
查看更多
初与友歌
4楼-- · 2018-12-31 10:17
Use finishAffinity() to clear all backstack with existing one.

Suppose, Activities A, B and C are in stack, and finishAffinity(); is called in Activity C, 

    - Activity B will be finished / removing from stack.
    - Activity A will be finished / removing from stack.
    - Activity C will finished / removing from stack.
查看更多
浅入江南
5楼-- · 2018-12-31 10:18

The given code works correctly. I have tried in the Application Life Cycle sample.

I haven't got B and C in the back stack after starting activity A with flag, FLAG_ACTIVITY_CLEAR_TOP

查看更多
十年一品温如言
6楼-- · 2018-12-31 10:18

This worked for me with onBackPressed:

public void onBackPressed()
{
    Intent intent = new Intent(ImageUploadActivity.this, InputDataActivity.class);

    Intent myIntent = new Intent(this, ImageUploadActivity.class);
    myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
   finish();
}
查看更多
其实,你不懂
7楼-- · 2018-12-31 10:19

It sounds to me like you need to start Activity C from Activity B by using startActivityForResult(). When you click a button in Activity C, call setResult(RESULT_OK) and finish() so Activity C is ended. In Activity B, you could have the onActivityResult() respond by also calling finish() on itself, and you'd then be taken back to Activity A.

查看更多
登录 后发表回答