goseta
goseta

Reputation: 790

Remove a range of activities from the stack

I have an activity A that go to B and then C, then D and then F and after I finish with F I want to jump to B again, but all activities C, D, and F need to be remove from history but still possible to go back from B to A, is there a way I can do this?? thanks!!

Upvotes: 1

Views: 637

Answers (2)

Barns
Barns

Reputation: 4848

You could intercept the back button pressed event in Activity F (or another event) and use an intent to get back to activity B.

@override
public void onBackPressed(){
    // Do what you need done here 
    Intent intent = new Intent(this, ActivityB.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    // if you need to pass data back to ActivityB
    //intent.putExtra("tagName", yourData);
    startActivity(intent);
    this.finish();
}

Adding the flag as xbadal suggested is on the right idea, but according the Android documentation it seems you need to use FLAG_ACTIVITY_CLEAR_TOP.

From Android documentation:

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 B, then C and D will be finished and B receive the given Intent, resulting in the stack now being: A, B.

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

Depending on which other flags are set at the time of calling the intent you may need to check to see which flags are already included by calling getFlags() and removing the conflicting ones with removeFlags(int).

Upvotes: 2

xbadal
xbadal

Reputation: 1375

try this. this will clear all your previous stack and start a new activity

 Intent intent= new Intent(F.this, B.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);
    ActivityCompat.finishAffinity(this)

Upvotes: 0

Related Questions