What is an Android PendingIntent?
Why PendingIntent is required ? I was thinking like
- Why the receiving application itself cannot create the
Intent
or - Why we cannot use a simple
Intent
for the same purpose.
E.g.Intent bluetoothIntent= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
If I send bluetoothIntent
to another application, which doesn't have permission android.permission.BLUETOOTH_ADMIN
, that receiving application cannot enable Bluetooth with startActivity(bluetoothIntent)
.
The limitation is overcome using PendingIntent
. With PendingIntent
the receiving application, doesn't need to have android.permission.BLUETOOTH_ADMIN
for enabling Bluetooth. Source.
A PendingIntent
is a token that you give to a foreign application (e.g. NotificationManager
, AlarmManager
, Home Screen AppWidgetManager
, or other 3rd party applications), which allows the foreign application to use your application's permissions to execute a predefined piece of code.
If you give the foreign application an Intent, it will execute your Intent
with its own permissions. But if you give the foreign application a PendingIntent
, that application will execute your Intent
using your application's permission.
A Pending Intent is a token you give to some app to perform an action on your apps' behalf irrespective of whether your application process is alive or not.
I think the documentation is sufficiently detailed: Pending Intent docs.
Just think of use-cases for Pending Intents like (Broadcasting Intents, scheduling alarms) and the documentation will become clearer and meaningful.
In my case, none of above answers nor google's official documentation helped me to grab the concept of PendingIntent
class.
And then I found this video, Google I/O 2013, Beyond the Blue Dot session. In this video, ex-googler Jaikumar Ganesh explains what PendingIntent
is, and that was the thing gave me the big picture of this.
Below is just transcription of above video (from 15:24).
So what's a pending intent?
It's a token that your app process will give to the location process, and the location process will use it to wake up your app when an event of interest happens. So this basically means that your app in the background doesn't have to be always running. When something of interest happens, we will wake you up. This saves a lot of battery.
This explanation becomes more clear with this snippet of code(which is included in the session's slide).
PendingIntent mIntent = PendingIntent.getService(...);
mLocationClient.requestLocationUpdates(locationRequest, mIntent);
public void onHandleIntent(Intent intent) {
String action = intent.getAction();
if (ACTION_LOCATION.equals(action)) {
Location location = intent.getParcelableExtra(...)
}
}