简体   繁体   中英

BroadcastReceiver not being called when pressing Notification Button

Inside the onCreate method of my Service I create a notification by doing the following:

String channelId = "001";
String channelName = "myChannel";

NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE);
channel.setLightColor(Color.BLUE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

if (manager != null) {
    manager.createNotificationChannel(channel);
    Notification notification;

    Intent myIntent = new Intent("alarmReceiver");

    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0);

    Notification.Action action = new Notification.Action.Builder(
            Icon.createWithResource(this, R.drawable.ic_stop_black_24dp),
            "action string",
            pendingIntent).build();


    //Modify notification badge
    notification = new Notification.Builder(getApplicationContext(), channelId).setOngoing(true)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setCategory(Notification.CATEGORY_SERVICE)
            .addAction(action)
            .build();

    startForeground(101, notification);
}

The alarmReceiver in the Intent above is registered in my manifest as shown below (I did the following after seeing this question):

<receiver android:name=".AlarmReceiver">
    <intent-filter>
        <action android:name="alarmReceiver" />
    </intent-filter>
</receiver>

and here is my AlarmReceiver class:

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("onReceive - ","was called");
    }
}

The notification is shown, as well as the button, but when I press the button nothing happens.

I'm not sure what I'm doing wrong. Any help would greatly be appreciated.

Set PendingIntent to foreground service, And potentially add a flag:

FLAG_UPDATE_CURRENT

PendingIntent pendingIntent = PendingIntent.getForegroundService(this, 0, myIntent, FLAG_UPDATE_CURRENT);

Your broadcast is Implicit , so if you want to use getBroadcast() it may be best to Explicitly declare the receiver by providing the intent with the componentName of the receiver.

eg:

intent.setComponent(new ComponentName("packagename","fully qualified class name"));

Have you declared the service in your manifest?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM