简体   繁体   中英

How to control activity stack/clear activity stack in Android

I have an application that goes as follows (Home being the launch activity):

D
C
B
A
Home

My flow goes as follows:

The user starts activity A from Home , which flows to B and C . When the user leaves activity C , I want A , B , and C to be destroyed. That is, if the user presses BACK in activity D , it goes back to Home .

The user must be able to control program flow normally through activity A , B , and C . So if they press the back button in activity C , it goes back to activity B .

I've looked at Intent flags such as CLEAR_TOP and NEW_TASK , but none of them seem to do what I want them to.

I'd appreciate any help!

Perhaps you are looking for FLAG_ACTIVITY_TASK_ON_HOME ? It requires API level 11 though:(

for API level <11, this can be done:

when starting activity B and C, use startActivityForResult(). When starting activity D, do this:

startActivity(D);
setResult(KILL_YOURSELF); //KILL_YOURSELF is some arbitrary int that you use to identify that the other activities should exit
finish(); //finish the activity

This will kill activity C. Then in activity A and B, override onActivityResult like this:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == KILL_YOURSELF) {
            setResult(KILL_YOURSELF);
            finish();
        }
    }

Thus activity B will finish, which in turn will trigger onActivityResult in A, so it will also finish.

Simply intercept the Back Button in Activity D, and upon intercepting the Back Button, head over to the Home Activity. You may / maynot want to finish 'D' activity as you are heading over to the Home Activity.

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