Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting Activity through notification: Avoiding duplicate activities

Tags:

android

So I am currently showing a notification. When the user clicks this noticiation, the application is started. The notification persists, to indicate that the service is running in the background.

Intent notificationIntent = new Intent(context, LaunchActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(1, notification);

However, I have detected a case where a bug appears. If the user starts the application through clicking the normal icon, and while the activity is running clicks the notification, then a new activity is started without the earlier one exiting, the later being on top of the earlier. And that is not all: Further clicks on the notification will create additional activities and place them on top of those already running. How can I prevent this? Is there a nice check to do to see if a certain activity is currently being shown or is loaded?

like image 996
pgsandstrom Avatar asked Feb 24 '10 14:02

pgsandstrom


3 Answers

That's the way it's supposed to be by default. You probably need to specify android:launchMode="singleTop" if you want to have a single instance only.
There are 4 launch modes, more info here: https://developer.android.com/guide/topics/manifest/activity-element.html

like image 100
yanchenko Avatar answered Oct 03 '22 07:10

yanchenko


When using the lanchMode="singleTask", if an instance of your activity already exists, Android does not re-create the Activity but launch it with the onNewIntent() method.

As documented by Android :

The system creates the activity at the root of a new task and routes the intent to it. However, if an instance of the activity already exists, the system routes the intent to existing instance through a call to its onNewIntent() method, rather than creating a new one.

Android documentation for activity mode

like image 21
Thomas Besnehard Avatar answered Oct 03 '22 07:10

Thomas Besnehard


As the two answers above have mentioned, you'll want to set the application's launch mode which is defined in the activity's definition in the manifest:

<activity
    android:name="com.company.ActivityName"
    android:launchMode="singleTask">
</activity>

Additionally, you may want to note, that despite FLAG_ACTIVITY_SINGLE_TOP being a valid Intent flag, there are no equivalent intent flags for singleTask or singleInstance.

See the launchMode section for more details on the different launch mode options: http://developer.android.com/guide/topics/manifest/activity-element.html#lmode

like image 36
TheIT Avatar answered Oct 03 '22 09:10

TheIT