How to click on a notification button with Java Android API?
Oct 13, 8:43pm
In Android, notification buttons are added with NotificationCompat.Builder.addAction() and wired to a PendingIntent (usually a BroadcastReceiver), since tapping the button fires the intent without opening the app.
1. Create the receiver
java
public class NotificationActionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if ("com.example.ACTION_ACCEPT".equals(action)) {
// handle accept
} else if ("com.example.ACTION_DECLINE".equals(action)) {
// handle decline
}
// Optionally dismiss the notification:
NotificationManagerCompat.from(context).cancel(0);
}
}
Use distinct request codes (0, 1, ...) per PendingIntent, otherwise extra flags can collide.
FLAG_IMMUTABLE is required on Android 12+ (API 31) unless you specifically need mutability.
Each notification can have up to 3 action buttons.
Tapping the body (not the buttons) is controlled separately via setContentIntent() — buttons never open the Activity directly unless you pass an Activity intent to addAction instead.
If the action should survive app process death / Doze mode (e.g. media controls), use a foreground service or MediaStyle actions instead of a plain receiver.
The same pattern works with a Service (via PendingIntent.getService) or an Activity (via PendingIntent.getActivity) if that fits your use case better.
Oct 13, 8:43pm
This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.