Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 260
GordonW Avatar asked Sep 06 '15 17:09

GordonW


People also ask

How do I transfer data from activity to activity?

We can send the data using the putExtra() method from one activity and get the data from the second activity using the getStringExtra() method.

How do you delete Backstacks on Android?

Use finishAffinity() to clear all backstack with existing one. Suppose, Activities A, B and C are in stack, and finishAffinity(); is called in Activity C, – Activity B will be finished / removing from stack. – Activity A will be finished / removing from stack.


2 Answers

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.

like image 52
Anindya Dutta Avatar answered Oct 10 '22 04:10

Anindya Dutta


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>
like image 15
Manish Avatar answered Oct 10 '22 04:10

Manish