Junior — Middle
What methods can be used to implement handling user actions triggered from push notifications?
sobes.tech AI
Answer from AI
Handling user actions from push notifications in Android is usually implemented through PendingIntent, which launches an Activity, Service, or BroadcastReceiver when the user interacts with the notification.
Main methods:
- PendingIntent for Activity: opens a specific screen of the app when the notification is tapped.
- PendingIntent for BroadcastReceiver: allows handling actions (e.g., buttons in the notification) without opening the UI.
- Using Notification Action Buttons: adding buttons with separate PendingIntents for different actions.
Example of adding an action button to a notification:
Intent snoozeIntent = new Intent(context, SnoozeReceiver.class);
PendingIntent snoozePendingIntent = PendingIntent.getBroadcast(context, 0, snoozeIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Reminder")
.setContentText("Time to take a break")
.addAction(R.drawable.ic_snooze, "Snooze", snoozePendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(notificationId, builder.build());
In BroadcastReceiver, you can handle the user's action, for example, snooze the notification or perform other logic.