Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
}
like image 338
dognose Avatar asked Jan 02 '13 12:01

dognose


3 Answers

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");
}
like image 98
ThePCWizard Avatar answered Sep 28 '22 01:09

ThePCWizard


You can try this in your Notification

Intent intent=new Intent();
intent.setAction("Activity1");

In the Activity override onNewIntent() method and get action so you can determine the activity is called or not.

like image 31
Ricky Khatri Avatar answered Sep 28 '22 02:09

Ricky Khatri


Better than using the reserved action field of your intent as specified by @ricintech, you could use an extra parameter in your pending intent and detect it in your onCreate method and in your onNewIntent metod inside your activity.

like image 33
Snicolas Avatar answered Sep 28 '22 01:09

Snicolas