简体   繁体   中英

Finish 2 activities when starting new activity

I have 4 activities: ABCD When starting the activity D from C, B and C should be removed from the stack. So, the sequence is like: A > B > C > D then D > A What I've tried doing when starting D from C is:

//create new Intent(C,D)
//setflags Intent.FLAG_ACTIVITY_CLEAR_TOP
//startActivity
//finish C

When onBackPressed is called in D, activity B is displayed. Seems like it didn't finish. And when checking the stack of activities in Layout Inspector I can see AB D. What do I do to remove B from stack upon calling D or upon onBackPressed of D? Note that I need B when C is started that's why I didn't try calling finish() when starting C. Thanks in advance

How about loading A Activity from D Activity.

Intent intent = new Intent(getBaseContext(), A.class);
startActivity(intent); 

One way to achieve this is when you press back on the activity D, you simply start your activity A with the flag FLAG_ACTIVITY_CLEAR_TOP . This will bring the already existing activity A to the front and clear all other activities.

@Override
void onBackPressed() {
     Intent intent = new Intent(this, A.class);
     intent.setFlags(FLAG_ACTIVITY_CLEAR_TOP);
     startActivity(intent);
}

Note: This will also clear the activity D from the stack so you won't be able to press back and go to the activity D.

只需使用:

startActivity(new Intent(this, A.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));

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