Resume application and stack from notification
I also had the same problem and try to resolve the problem like @GrAnd's answer:
final Intent notificationIntent = new Intent(context,YourActivity.class);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
This works, no doubts about it but the problem is when you set your intent as ACTION_MAIN. Then you will not be able to set any bundle to the intent. I mean, your primitive data will not be received from the target activity because ACTION_MAIN can not contain any extra data.
Instead of this, you can just set your activities as singleTask and call your intent normally without setting ACTION_MAIN and receive the intent from onNewIntent() method of your target activity.
But beaware if you call, super.onNewIntent(intent); then a second instance of the activity will be created.
For situations where you don't want / can't hard code the launcher activity this solution works
Intent i = getPackageManager()
.getLaunchIntentForPackage(getPackageName())
.setPackage(null)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, 0);
return new NotificationCompat.Builder(context)
...
.setContentIntent(pendingIntent)
.build();
The setPackage(null) part was key in my case since without it the app did not resume to previous task. I compared my intent with the intent from the Android launcher and noticed that pkg was not set there so that's how I came up with removing package name from the intent.
My particular situation was that the notification was created in a library so there I could not know what the launcher activity would be.
Just use the same intent filters as Android uses when it launches the app:
final Intent notificationIntent = new Intent(context, YourActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
As the Intent
you created to open your Activity
from the notification bar is the same as Android used for launching your app, the previously opened Activity
will be shown instead of creating a new one.