My app has notifications, which - obviously - without any flags, start a new activity every time so I get multiple same activities running on top of each other, which is jus
This is old thread, but for all those who is still seeking for answer, here is my solution. It is purely in code, without manifest settings:
private static PendingIntent prepareIntent(Context context) {
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
return PendingIntent.getActivity(context, NON_ZERO_REQUEST_CODE, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
Here FLAG_ACTIVITY_SINGLE_TOP opens existing activity if it is at the top of task stack. If it is not at the top, but inside stack, FLAG_ACTIVITY_CLEAR_TOP will remove all activities on top of target activity and show it. If activity is not in the task stack, new one will be created. A crucially important point to mention - second parameter of PendingIntent.getActivity(), i.e. requestCode should have non-zero value (I even called it NON_ZERO_REQUEST_CODE in my snippet), otherwise those intent flags will not work. I have no idea why it is as it is. Flag FLAG_ACTIVITY_SINGLE_TOP is interchangeable with android:launchMode="singleTop" in activity tag in manifest.
I tried this, and it worked even though the IDE was complaining about the code
Intent notificationIntent = new Intent(THIS_CONTEXT, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
PendingIntent intent = PendingIntent.getActivity(THIS_CONTEXT, 0, notificationIntent, Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(THIS_CONTEXT)
.setSmallIcon(R.drawable.cast_ic_notification_0)
.setContentTitle("Title")
.setContentText("Content")
.setContentIntent(intent)
.setPriority(PRIORITY_HIGH) //private static final PRIORITY_HIGH = 5;
.setAutoCancel(true)
/*.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)*/;
NotificationManager mNotificationManager = (NotificationManager) THIS_CONTEXT.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());