Search code examples
androidnotificationsandroid-pendingintent

Determine if Activity is called by a Notification


I am using an Activitiy with various Tabs on it. From a different part of the application, Notifications are created to tell the user that something has changed. I now managed to Call the Activity, when the user clicks on the Notification. But how can i determine wheter a Activity is created the "normal" way during runtime or by clicking on the notification?

(Depending on the notification clicked, i want to forward to another tab instead of showing the main Tab.)

Intent intent = new Intent(ctx, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent, 0);

        // TODO: Replace with .Build() for api >= 16
        Notification noti = new Notification.Builder(ctx)
                .setContentTitle("Notification"
                .setContentText(this.getName())
                .setSmallIcon(R.drawable.icon)
                .setContentIntent(pendingIntent)
                .setDefaults(
                        Notification.DEFAULT_SOUND
                                | Notification.DEFAULT_LIGHTS)
                .setAutoCancel(true)
                .getNotification();

        NotificationManager notificationManager = (NotificationManager) ctx
                .getSystemService(Context.NOTIFICATION_SERVICE);

        // Hide the notification after its selected
        notificationManager.notify(this.getId(), noti); 

This successfully calls my MainActivity. But is there some Method that is called when the Activity is triggered by the pendingIntent?

Thought about to define something like this in the Main Activity:

onTriggeredByNotification(Notification noti){
     //determinte tab, depending on Notification.
}

Solution

  • Pass a boolean value from notification and check for the same in the onCreate method of the activity.

     Intent intent = new Intent(ctx, MainActivity.class);
     intent.putExtra("fromNotification", true);
    

    ...

    if (getIntent().getExtras() != null) {
      Bundle b = getIntent().getExtras();
      boolean cameFromNotification = b.getBoolean("fromNotification");
    }