2

I will be starting activities in the following series:

A->B->C->D Now I want to start another activity suppose E from D and clear the stack but keep activity A as root activity. After starting E the stack should be A->E. How can I achieve this?

Aju
  • 4,597
  • 7
  • 35
  • 58
  • Possible duplicate of [Android Popping off the Activity Stack](https://stackoverflow.com/questions/3517063/android-popping-off-the-activity-stack) – matoni Aug 11 '17 at 08:31
  • @matoni this not duplicate. The one you have referred is telling about clearing the task. Here I am asking about start an activity and clear the stack still the root activity should be there. – Aju Aug 11 '17 at 13:52

2 Answers2

1

You can acheive that with TaskStackBuilder. This dude lets you rebuild stack which you need. You need somethink like this:

final Intent activityAIntent = new Intent(this, ActivityA.class);
activityAIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

TaskStackBuilder.create(this)
                .addNextIntent(activityAIntent)
                .addNextIntent(new Intent(this, ActivityE.class))
                .startActivities();
Anton Potapov
  • 1,265
  • 8
  • 11
0

When your start activity E from D first clear flag top Or finishAffinity(). So all your previous activity is closed. and open first activity from backpress.

Add OnBackPressed method in E Activity.

Like this

   @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = new Intent(getApplicationContext(), AActivity.class);
        startActivity(intent);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            finishAffinity();
        } else {
            finish();
        }
    }
Jigar Patel
  • 1,550
  • 2
  • 13
  • 29