Jake
Jake

Reputation: 16837

Android - use of pending intent with notification

I am reading a tutorial on pending intent and how it is used with notification manager.

In that page, the following code is mentioned :

 Intent intent = new Intent(this, NotificationReceiverActivity.class);
 PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

 Notification noti = new Notification.Builder(this)
    .setContentTitle("New mail from " + "[email protected]")
    .setContentText("Subject").setSmallIcon(R.drawable.icon)
    .setContentIntent(pIntent)
    .addAction(R.drawable.icon, "Call", pIntent)
    .addAction(R.drawable.icon, "More", pIntent)
    .addAction(R.drawable.icon, "And more", pIntent).build(); 


 NotificationManager notificationManager = 
     (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

 // hide the notification after its selected
 noti.flags |= Notification.FLAG_AUTO_CANCEL;

 notificationManager.notify(0, noti);

I want to ask why the notification manager needs to be provided a pending intent (why does it need my app's identity to send an intent) ?

Why can't it be just given an intent ?

Edit : Please don't answer with the definition of pending intent. I know what a pending intent is. What I am interested in finding is why can't the notification just use a normal intent with some API like startActivity().

Upvotes: 3

Views: 1635

Answers (1)

tar
tar

Reputation: 1568

An Intent requires a context. If your application is not running then there is no context. Using a PendingIntent allows the system to invoke an intent with your application's permissions (context).

From http://www.simplecodestuffs.com/what-is-pending-intent-in-android/:

The reason it’s needed is because an Intent must be created and launched from a valid Context in your application, but there are certain cases where one is not available at the time you want to run the action because you are technically outside the application’s context (the two common examples are launching an Activity from a Notification or a BroadcastReceiver.

Also see this StackOverflow answer.

Upvotes: 1

Related Questions