3

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 " + "test@gmail.com")
    .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().

Jake
  • 16,329
  • 50
  • 126
  • 202

1 Answers1

1

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.

Community
  • 1
  • 1
tar
  • 1,538
  • 1
  • 20
  • 33
  • But still .. why does a notification need my app context ? If it has to just send an intent, it can easily do so with normal intent and using something like startActivity .. – Jake Jul 28 '14 at 04:13
  • Intent object itself doesn't depend on context. So are you indicating that to use an API like startActivity, the notification has no context object available ? – Jake Jul 28 '14 at 04:19
  • 1
    To send a "startActivity" intent, the syntax is `context.startActivity(intent)`. That requires the context. If the system invoked that line when the user taps the notification (and after your app is closed), the context would already be null. From the same link, "It is a token that you give to a foreign application which allows the foreign application to use your application’s permissions to execute a predefined piece of code." – tar Jul 28 '14 at 04:22