Declare Activity A as SingleTop by using [android:launchMode="singleTop"] in Android manifest. Now add the following flags while launching A from anywhere. It will clear the stack.
Standard This is the default launch mode of activity (If not specified). It launches a new instance of an activity in the task from which it was launched.
I think you need to make your activity B singleInstance
that if it's already create you don't want to create again, that is launch mode of the activity can be defined in manifest android:launchMode
that defines how the activity will be instanciated.
in your case use android:launchMode="singleInstance"
You can use flag Intent.FLAG_ACTIVITY_NEW_TASK. If the activity is already running it will bring that to front instead of creating new activity.
If you add Intent.FLAG_ACTIVITY_CLEAR_TOP with this, then all the activities after this activity in the backstack will be cleared.
If the activity will be on the top if already started, set the FLAG_ACTIVITY_SINGLE_TOP flag
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
mContext.startActivity(intent);
Approaches android:launchMode="singleInstance"
and just adding flags to the Intent
do not work for me.
What works is that:
In the code where activity gets started:
Intent intent = new Intent(activity, ActivityThatHasToBeStarted.class);
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
startActivity(intent);
In the ActivityThatHasToBeStarted
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
finish();
return;
}
// Code for this creation
}
You may consider using android:launchMode="singleTop"
instead of android:launchMode="singleInstance"
Good article about the differences
If you don't need the second activity anymore, it is good practise to finish it, then you should do this on the second activity after the operation is ended:
startActivity(new Intent(this, FirstActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
finish();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With