Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: prevent activity to be instantiated more than once

I was going through Android Task and Back Stack documentation and at one point they mention this:

if your application allows users to start a particular activity from more than one activity, a new instance of that activity is created and pushed onto the stack (rather than bringing any previous instance of the activity to the top). As such, one activity in your application might be instantiated multiple times (even from different tasks), as shown in figure 3. As such, if the user navigates backward using the Back button, each instance of the activity is revealed in the order they were opened (each with their own UI state)

Let's take an example:

I have Activity A Starting Activity B which Starts Activity C which starts D.

Stack is A->B->C->D now it is possible to Start C from D so when we start C from D stack will be

A->B->C->D->C

Now instead of this standard behavior I want Activity to have only 1 instance or only 1 entry in the Back Stack. "SingleTop" will not work since Activity C was not on top when we started it from D.

I might be missing something but is there any way to achieve this making sure an activity has only 1 backstack entry?

Thanks Pranay

like image 616
Pranay Airan Avatar asked Dec 18 '25 00:12

Pranay Airan


2 Answers

Use Intent.FLAG_ACTIVITY_CLEAR_TOP, e.g.:

    Intent intent = new Intent(context, <your_activity_here>);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    context.startActivity(intent);

So, all the activities in stack after activity C will be finished automatically. If you use the specified flag

A->B->C->D

will become

A->B->C

like image 84
olshevski Avatar answered Dec 20 '25 14:12

olshevski


You can also use android:launchMode="singleInstance" in your activity tag in manifest

like image 39
maninder singh Avatar answered Dec 20 '25 13:12

maninder singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!