Reputation: 840
I have a common menu on my app with icons. Clicking an icon will start an Activity. Is there a way to know if an activity is already running and prevent it from starting multiple times (or from multiple entries)? Also can I bring an activity that is in onPause state to the front?
Upvotes: 28
Views: 24308
Reputation: 113
This works for me :
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
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.
also, you can use FLAG_ACTIVITY_NEW_TASK
with it.
then the code will be :
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
Upvotes: 1
Reputation: 77
please add this in menifest file
<activity
android:name=".ui.modules.profile.activity.EditProfileActivity"
android:launchMode="singleTask" // <<this is Important line
/>
Upvotes: -1
Reputation: 4652
I got it perfectly working by doing the following. In the caller activity or service (even from another application)
Intent launchIntent = getPackageManager().getLaunchIntentForPackage(APP_PACKAGE_NAME);
//the previous line can be replaced by the normal Intent that has the activity name Intent launchIntent = new Intent(ActivityA.this, ActivityB.class);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launchIntent);
and in the manifest of the receiver activity (the I want to prevent opening twice)
<activity android:name=".MainActivity"
android:launchMode="singleTask"
>
Upvotes: 5
Reputation: 451
Just use
Intent i = new Intent(ActivityA.this, ActivityB.class);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
Upvotes: 0
Reputation: 27549
In your activity declaration in Manifest file, add the tag android:launchMode="singleInstance"
Upvotes: 19
Reputation: 1668
create an instance of your activity which you dont want to start multiple times like
Class ExampleA extends Activity {
public static Activity classAinstance = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
classAinstance = this;
}
}
Now where ever u want to crosscheck i mean prevent it from starting multiple times, check like this
if(ExampleA.classAinstance == null) {
"Then only start your activity"
}
Upvotes: -1
Reputation: 37729
Use this:
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
while starting Activity
.
from documentation:
If set in an Intent passed to Context.startActivity(), this flag will cause the launched activity to be brought to the front of its task's history stack if it is already running.
Upvotes: 57