18

In my application I notify the user with notifications, if something special happens:

public void triggerNotification(String msg) {
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Intent contentIntent = new Intent(this, ABC.class);
        Notification notification = new Notification(R.drawable.icon, msg, System.currentTimeMillis());
        notification.setLatestEventInfo(this, "ABC", msg, PendingIntent.getActivity(this.getBaseContext(), 0, contentIntent, PendingIntent.FLAG_CANCEL_CURRENT));
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(notificationCounter, notification);
        notificationCounter++;
}

If the user clicks on the Notification, the onCreate() method is called. But I want that a specific method in my app is called, or if the app is not in the foreground, that it is brought back to the foreground.

I know there are lots of tutorials that explain how to handle notifications, but I just don't understand them completely and wasn't ever able to implement the things like I'd like to.

3 Answers3

18

To bring your app to the foreground if it is running already you need to set different flags on your intent:

contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

For running a specific method you could just pass extra information along with the intent and interpret it in your application to decide which method to run.

pheelicks
  • 7,461
  • 2
  • 45
  • 50
stealthcopter
  • 13,964
  • 13
  • 65
  • 83
10

The recommendation to use FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_SINGLE_TOP only partially solves the problem. The activity in the Android manifest should also have these settings applied so that launching the activity from the home screen has the same behavior. Without these properties multiple instances of the activity can be launched.

<activity android:name="foo"
          android:clearTaskOnLaunch="true"
          android:launchMode="singleTop"
          android:label="@string/app_name">
user2038378
  • 141
  • 1
  • 2
0

I've discovered that if you use Intent contentIntent = new Intent(this, ABC.class); this calls onCreate(); regardless of the flags set.

Use Intent contentIntent = getIntent(); to skip onCreate(); and that moves to onStart();

adam2645
  • 61
  • 2
  • 2
  • I can't seem to find a way to the activity context on the FirebaseMessagingService in order to call getIntent() – Donki Oct 14 '22 at 11:57