GordonW
GordonW

Reputation: 1120

Delete old activity instance when starting a new activity

I'm looking to delete/remove an old activity instance when a new instance (of same activity) is created, however I need to maintain all other activities in back-stack (therefore FLAG_ACTIVITY_CLEAR_TOP won't suffice).

E.g. say I have activities A, B & C. I start: A -> B -> C -> B. On the start of the second B activity I need to remove the existing B activity. Therefore I now have: A -> C -> B running...

Any help appreciated.

Upvotes: 16

Views: 16666

Answers (5)

Bukka
Bukka

Reputation: 1

This solved mine

@Override
 protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    finish();
    startActivity(intent);
   
}

Upvotes: 0

beginner
beginner

Reputation: 2508

 @Override
  protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        finish();
        startActivity(intent);
       
  }

In manifest file

    <activity
      android:name=".MyActivity"
      android:launchMode="singleTask" > 
   </activity>

Upvotes: 2

Manish
Manish

Reputation: 1091

I am able to do that by overriding onNewIntent

    @Override
protected void onNewIntent(Intent intent) {


        Bundle extras = intent.getExtras();
        Intent msgIntent = new Intent(this, MyActivity.class);
        msgIntent.putExtras(extras);
        startActivity(msgIntent);
        finish();
        return;

    super.onNewIntent(intent);
}

make activity single task

 <activity
        android:name=".MyActivity"
        android:launchMode="singleTask" >
    </activity>

Upvotes: 15

GordonW
GordonW

Reputation: 1120

It seems that deleting the activity is not as easy as I would have imagined therefore not a complete answer but I'm going to go with using FLAG_ACTIVITY_REORDER_TO_FRONT. This will not kill the existing activity but instead move it to top of stack.

Intent intent = new Intent(ctx, Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);

This will allow for the activity navigation outlined above.

I'm still interested if someone knows of a means to clear the actual activity.

Upvotes: 11

Anindya Dutta
Anindya Dutta

Reputation: 1982

You could use the Intent flags to remove the earlier task. Hopefully this helps.

Intent intent = new Intent(this, Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

This flag will cause any existing task that would be associated with the activity to be cleared before the activity is started. That is, the activity becomes the new root of an otherwise empty task, and any old activities are finished.

Upvotes: 19

Related Questions