Intent - if activity is running, bring it to front, else start a new one (from notification) Intent - if activity is running, bring it to front, else start a new one (from notification) android android

Intent - if activity is running, bring it to front, else start a new one (from notification)


You can use this:

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

which will work similar to "singleInstance" but it won't have that weird animation.


I think the best way to do it and in a simple manner is to start the activity normally, but set that activity in the manifest with the singleInstance property. With this you practically approach both issues you are having right now, by bringing the activity to the front all the time, and letting the OS automatically create a new one if no activity exists or bring to the front the currently existing activity (thanks to the singleInstance property).

This is the way an activity is declared as a single instance:

<activity    android:name=".YourActivity"   android:launchMode="singleInstance"/>

Also to avoid a choppy animation when launching through singleInstance, you could use instead "singleTask", both are very similar but the difference is explained here as per Google's documentation:

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

singleInstance is the same as "singleTask", except that the system doesn't launch any other activities into the task holding the instance. The activity is always the single and only member of its task.

Hope this helps.

Regards!


I think what you need is in singleTop Activity, rather than a singleTask or singleInstance.

<activity android:name=".MyActivity"          android:launchMode="singleTop"          ...the rest... >

What the documentation says does perfectly suit your needs:

[...] a new instance of a "singleTop" activity may also be created to handle a new intent. However, if the target task already has an existing instance of the activity at the top of its stack, that instance will receive the new intent (in an onNewIntent() call); a new instance is not created. In other circumstances — for example, if an existing instance of the "singleTop" activity is in the target task, but not at the top of the stack, or if it's at the top of a stack, but not in the target task — a new instance would be created and pushed on the stack.

On top of that (no pun intended), I had exactly the same need as you. I tested all the launchMode flags to figure out how they actually behave in practice and as a result singleTop is actually the best for this: no weird animation, app displayed once in the recent applications list (unlike singleInstance that displays it twice due to the fact it doesn't allow any other Activity to be part of its task), and proper behavious regardless the target Activity already exists or not.