Reputation: 564
I have a notification and am trying to run a method in an activity when a specific button in the notification is pressed. I am creating the broadcastReceiver in onCreate:
//broadcast receiver stuff
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Code to run
if (intent.getAction().equals("stop")){
StartButtonClick();
}
}
};
registerReceiver(broadcastReceiver, new IntentFilter("stop"));
Then I create the notification in the same activity (not in onCreate though):
private void ShowNotification(){
//add intent for app to resume when notification is clicked
PendingIntent reopenAppIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
//add intent for app to stop service when stop button in notification is clicked
//this is the intent I am creating for the notification button
Intent stopIntent = new Intent("stop");
PendingIntent stopPendingIntent = PendingIntent.getService(this, 1, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//create notification
NotificationCompat.Builder notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setContentTitle("Messaging in progress")
.setContentText("User is late")
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSmallIcon(R.drawable.ic_message)
.setContentIntent(reopenAppIntent)
.addAction(R.drawable.ic_message, "Stop", stopPendingIntent); //here I am adding the intent for the butt that I want to activate the broadcastReceiver
notificationManager.notify(1, notification.build());
}
When I click the button in the notification, nothing happens. I even put a break point on the broadcastReceiver's if-statement and nothing ever happens on the button press.
Upvotes: 0
Views: 212
Reputation: 5103
Try this
PendingIntent stopPendingIntent = PendingIntent.getBroadcast(this, 1, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);
instead of
PendingIntent stopPendingIntent = PendingIntent.getService(this, 1, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Upvotes: 1