I am developing an android library which uses FCM to receive a notification in the background. Upon tapping the notification, the user should be redirected to the last open activity - not the launch activity. I use the flag FLAG_ACTIVITY_NEW_TASK
to accomplish this, and the app works as expected in two cases: 1. if I build the app directly over USB in android studio, and 2. If I download and install an .apk of the app, kill the app, and then restart it.
However, if I install the application as an .apk, I get the following behavior:
1. The app opens on the launch activity A.
2. I navigate to activity B and put the app in the background
3. I receive a notification and tap on it. The app opens on activity A instead of activity B as expected.
I don't understand the difference between installing the application as an apk and installing it over usb. Is there some difference in the activity that makes FLAG_ACTIVITY_NEW_TASK
treat it like a separate activity? Here's my code:
Intent packageIntent = applicationContext.getPackageManager().getLaunchIntentForPackage(packageName);
String mainClassName = packageIntent.getComponent().getClassName();
Intent intent = new Intent(applicationContext, NotificationTapService.class);
(Note that the reason I'm setting up an intermediate intent that launches a service to reopen the last activity is because the service also calls some unrelated analytics functionality)
PendingIntent pendingIntent = PendingIntent.getService(applicationContext, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(applicationContext, applicationContext.getString(R.string.channel_id))
.setSmallIcon(notificationResourceId)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(messageBody))
.setSound(defaultSoundUri)
.setVibrate(new long[] {1000, 1000, 1000, 1000, 1000})
.setLights(Color.BLUE, 3000, 3000)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_MAX);
NotificationManager notificationManager = (NotificationManager) applicationContext.getSystemService(applicationContext.NOTIFICATION_SERVICE);
notificationManager.notify(messageId, notificationBuilder.build());
(setting up the intent to reopen the activity at the top of the back stack) (from NotificationTapService)
Intent activityIntent = new Intent(applicationContext, Class.forName(intent.getExtras().getString(CLASS_NAME)));
activityIntent.setAction(Intent.ACTION_MAIN);
activityIntent.addCategory(Intent.CATEGORY_LAUNCHER);
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activityIntent);