How to use PendingIntent in an Android app?

In Android development, a PendingIntent is a token that you give to another application (e.g., NotificationManager, AlarmManager) that allows it to execute a predefined piece of code on your behalf, even if your application's process is not alive. It's commonly used for notifications, alarms, and services.

Using PendingIntent in an Android app

Here’s a simple example of how to create and use a PendingIntent to launch an activity when a notification is tapped.

First, add the necessary permissions in your AndroidManifest.xml:

<uses-permission android:name="android.permission.VIBRATE"/>

Now, in your activity, you can create a notification with a PendingIntent:

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Intent intent = new Intent(this, TargetActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("New Message") .setContentText("You have received a new message.") .setSmallIcon(R.drawable.ic_message) .setContentIntent(pendingIntent) // Set the PendingIntent here .setAutoCancel(true) .build(); notificationManager.notify(NOTIFICATION_ID, notification);

This code will create a notification that, when tapped, will open the TargetActivity. The PendingIntent is necessary here because it allows the NotificationManager to start the specified activity.


PendingIntent Android development Android notifications AlarmManager code execution notification tap action