I have the following activities: A -> B -> C -> D. If I press the back button from Activity D I want to go back to A. This is the code:
Activity A
// Launch Activity B
Intent intent = new Intent();
intent.setClass(ActivityA.this, ActivityB.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Activity B
// Launch Activity C
Intent intent = new Intent();
intent.setClass(ActivityB.this, ActivityC.class);
startActivity(intent);
Activity C
// Launch Activity D
Intent intent = new Intent();
intent.setClass(ActivityC.this, ActivityD.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
In Activity D I press back and I want to go back to Activity A. I do not want to use finish() each time I open an activity because when I am in Activity C I want to be able to go back to B, but when I am in Activity D, I want to go directly to A, but unfortunately the current implementation makes the app to close.
Maybe this will work out:(Remember to override the onBackPressed)
Meaning of the Flag:
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.
For example, consider a task consisting of the activities: A, B, C, D. If D calls startActivity() with an Intent that resolves to the component of activity A, then B, C and D will be finished and A receive the given Intent, resulting in the stack now being: A.