0

I'm using single activity architecture in my app. Now I'm stuck with handing notifications. I'm receiving notification from firebase and when app is on background, the google play services handle such notifications great. When it's tapped it brings the app from background to foreground (it does't recreate activity / app). I need to have the same behaviour for notification received while the app is on foreground. Therefore I override onMessageReceived() in my firebase service and create new notification here. I tried many variation of Intent's Flags passed to the notification and launchMode in manifest but it always results into activity recreation (activity has different hashcode and it's onCreate() it's called) after tapping on notification created by onMessageReceived(). Here is the code:

@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    Logger.d("Msg received " + remoteMessage.getNotification().getTitle());

    Intent intent = new Intent(this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notification = new NotificationCompat.Builder(this, FCM_CHANNEL_ID)
            .setContentTitle(remoteMessage.getNotification().getTitle())
            .setContentText(remoteMessage.getNotification().getBody())
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setAutoCancel(true)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody()))
            .build();
    NotificationManagerCompat manager = NotificationManagerCompat.from(getApplicationContext());
    manager.notify(FCM_NOTIFICATION_ID, notification);
}


manifest: android:launchMode="singleTask"

Any idea what to change to prevent activity recreation? (I'm testing on android 10, MainActivity extends AppCompatActivity) Thanks.

msmetak
  • 43
  • 6

3 Answers3

1

Finally I get it work. All magic was done by adding those two lines to my code.

intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);

Original answer

msmetak
  • 43
  • 6
0

Did you try this?

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Juan Sancho
  • 321
  • 1
  • 7
0

Use the Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK flags.

This will start activity as the root of the stack.

akhil nair
  • 1,371
  • 1
  • 11
  • 19