为什么通知 PendingIntent 不起作用?

Why notification PendingIntent doesn't work?

我有一个通知和一个 "Stop" 按钮。这个按钮的PendingIntent指的是BackgroundTaskService's内classNotificationReceiver。但是当我点击 "Stop" 按钮时没有任何反应。怎么了?

通知实验室 class:

class NotificationsLab{
    /*...Some constructors, variables and other stuff here...*/

    public Notification createNotification(UUID taskId){
        Intent intent= new Intent(mContext, BackgroundTaskService.NotificationsReceiver.class);
        intent.setAction(BackgroundTaskService.CANCEL_TASK_ACTION);
        intent.putExtra(TASK_ID, taskId);
        PendingIntent cancelPendingIntent =
                PendingIntent.getBroadcast(mContext, 0, intent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, CHANNEL_ID)
                .addAction(R.drawable.ic_file_gray_classic_24dp, "Stop",
                        cancelPendingIntent)
                .setProgress(100, 0, false);
        return builder.build();
    }
}

BackgroundTaskServiceclass:

class BackgroundTaskService extends Service{
    private BroadcastReceiver mReceiver = new NotificationReceiver();
    public IBinder onBind(Intent intent) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(CANCEL_TASK_ACTION);
        registerReceiver(mReceiver, filter);
        return mIBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter filter = new IntentFilter();
        filter.addAction(CANCEL_TASK_ACTION);
        registerReceiver(mReceiver, filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(CANCEL_TASK_ACTION);
        registerReceiver(mReceiver, filter);
        return super.onStartCommand(intent, flags, startId);
    }
    public static class NotificationsReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("TAG", "You will never see this message!!!");
        }
    }
}

因此,Log.d 应该打印的消息永远不会出现。我可以用它做什么?

问题是我忘记将我的 BroadcastReceiver 添加到清单中。

刚刚添加 <receiver android:name=".services.BackgroundTaskService$NotificationsReceiver"/> 到清单