return back and skip one activity android onbackpressed

2.4k views Asked by At

Here is my case assuming that I have those activities A -> B -> C -> D

I want to come back to A when the user click on the back button when he is in D but also I want to come back to B when the user click on the back button of C

I thought to call finish when I go to C from B, but in this case I can't return to B if I click on back of C

how can I fix this issue without calling onBackPressed on two activities?

thanks

3

There are 3 answers

0
Neil Townsend On

When you start each activity, you will need to use

startActivityForResult()

And then have a system of flags saying who is being stopped which are passed back. So, activity D:

timeToEnd() {
    setResult(RESULT_D_CLOSING);
    finish();
}

And then in A, C, D

onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(resultCode)
    case RESULT_D_CLOSING:
        // Close on upwards
        setResult(RESULT_D_CLOSING);
        finish();
    case ....
        // You get the idea
    }
}
0
nitesh goel On

Have you tried using FLAG_ACTIVITY_CLEAR_TOP flag in your intent (used to start "A" from "D")?

http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

0
Ali On

You have 2 options here. You can either start the activities with startActivityForResult and then onBackPressed of each activity pass a flag back that tells the activity to either exit of stay open.

An other option would be to implement A,B,C,D as fragments in the same activity put all the fragments on the backstack as you open them and then onBackPress you can programmatically loop through the backstack to see what you want to do.