PX Developer PX Developer - 1 year ago 107
Android Question

Notification click: activity already open

I have an application with notifications that open a certain activity if I click them. I want that, if I click the notification and the activity is already opened, it's not started again, but just brought to front.

I thought I could do it with the flag

, but it keeps opening it again so I have the activity twice.

This is my code:

event_notification = new Notification(R.drawable.icon,
mContext.getString(R.string.event_notif_message), System.currentTimeMillis());
Intent notificationIntent = new Intent(mContext, EventListActivity.class);
sendNotification(event_notification, notificationIntent, mContext.getString(R.string.event_notif_title),

Can I manage it with flags or should I store a variable in SharedPreferences to check if it's opened or not?



You need to set the launchMode attribute of the Activity you are starting to singleTop. This will cause incoming Intents to be delivered to the existing instance rather than starting a new instance when that Activity is already at the top of the task's stack.

This is done in the manifest by adding android:launchMode="singleTop" to the <activity> element. To access the latest Intent (if you are interested in any data that may have passed in with it), override onNewIntent() in your Activity.