Dima Bukharev
Dima Bukharev

Reputation: 43

Why notification PendingIntent doesn't work?

I have a notification and a "Stop" button on it. The PendingIntent of this button refers to BackgroundTaskService's inner class NotificationReceiver. But when I click the "Stop" button nothing happens. What is wrong?

NotificationsLab 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();
    }
}

BackgroundTaskService class:

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!!!");
        }
    }
}

So, the message that the Log.d should print will never appear. What can I do with it?

Upvotes: 2

Views: 385

Answers (1)

Dima Bukharev
Dima Bukharev

Reputation: 43

The problem was that I forgot to add my BroadcastReceiver to the manifest.

Just added <receiver android:name=".services.BackgroundTaskService$NotificationsReceiver"/> to the Manifest

Upvotes: 1

Related Questions