Introduction to Pending Intents in Android

Pending intents are a bit different than the regular intents. The PendingIntent class provides a method for creating Intents that can be fired on your application’s behalf by the system, or another application, at a later point of time. By using the PendingIntent we can communicate with a foreign application like the Camera, etc. A Pending Intent is commonly used to package Intents that will be fired in response to a future event, such as when a user touches a Notification, etc.

The PendingIntent class offers static methods to construct Pending Intents used to start an Activity, to start background or foreground Services, or to broadcast implicit or explicit Intents. The PendingIntent class includes these static constants:

requestCode is an integer that is assigned to the pending intent, so refer to it when we want to delete it.

flags is used to handle multiple intents, using same Pending intent instance.

int flags = 0;
int requestCode = 0;

// Here we are starting an Activity
Intent startActivityIntent = new Intent(this, MyActivity.class);

PendingIntent.getActivity(this, requestCode, startActivityIntent, flags);

// Here we are starting a Activity
Intent startServiceIntent = new Intent(this, MyService.class);

PendingIntent.getService(this, requestCode, startServiceIntent, flags);

// Starting a foreground Service (Requires API Level 26 or higher)
Intent startForegroundServiceIntent = new Intent(this, ForgroundService.class);
PendingIntent.getForegroundService(this, requestCode, startForegroundServiceIntent flags);

// Broadcast an Intent to an explicit Broadcast Receiver
Intent broadcastExplicitIntent = new Intent(this, Receiver.class);
PendingIntent.getBroadcast(this, requestCode, broadcastExplicitIntent, flags);

// Broadcast an implicit Intent
Intent broadcastImplicitIntent = new Intent(MY_NEW_INTENT_ACTION);
PendingIntent.getBroadcast(this, requestCode, broadcastImplicitIntent, flags); 

Because Pending Intents are triggered outside the scope of the application, it’s important to consider the user’s context when these Intents are likely to be executed. Like an Intent that starts a new activity should be used only in response to a direct user action, such as selecting a notification, etc. So by using the Pending Intent you are instructing the system that you want to execute a task in the future.

Leave a Reply

Your email address will not be published. Required fields are marked *

Trending