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.
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.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?