Starting Activity through notification: Avoiding duplicate activities

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?


Solution 1:

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

Solution 2:

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

Solution 3:

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