I have an activity that creates notifications using the following code:
Notification notification = new Notification(icon,
tickerText, 0);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Context context = getApplicationContext();
CharSequence contentText = getString(R.string.subtitle);
Intent notificationIntent = new Intent(getBaseContext(),
MainActivity.class);
notificationIntent.putExtra("num", Integer.toString(i));
Intent deleteIntent = new Intent(getBaseContext(),
DeleteActivity.class);
deleteIntent.putExtra("num", Integer.toString(i));
PendingIntent contentIntent = PendingIntent.getActivity(
getBaseContext(), ran, notificationIntent, 0);
PendingIntent deletePendingIntent = PendingIntent
.getActivity(getBaseContext(), ran, deleteIntent, 0);
notification.setLatestEventInfo(context, text, contentText,
contentIntent);
notification.deleteIntent = deletePendingIntent;
final int NOTIF_ID = ran;
mNotificationManager.notify(NOTIF_ID, notification);
I keep a list of all the notifications from my app that are currently showing.
When the notification is clicked, it opens the MainActivity. I have some code in the onResume() to delete the notification from the list. This works fine.
When the notification is dismissed, it triggers DeleteActivity, which also deletes it from my list. This also works fine.
The problem is, if MainActivity is already open, and the notification is clicked, the onResume() doesn’t run again, and so the notification is gone, but it’s not deleted from the list of notifications that the app thinks are showing.
I’m wondering if there’s any way I can execute a particular piece of code (or even just restart the whole activity) when the intent is received. I know I could just set it to use DeleteActivity instead but I’d rather have it open the MainActivity.
You can catch the notification click in your Activity by overiding onNewIntent. This is what I do in my App.