Global broadcast or local broadcast with PendingIntent

2.3k views Asked by At

I run a background task in an IntentService. I show progress in notification bar (with NotificationManager), and want to cancel the task if somebody click on that notification.

I implemented it successfully with broadcast service. However, I was thinking is it possible to do the same with localBroadcast.

if I change "registerReceiver" to "LocalBroadcastManager.getInstance(this).registerReceiver", the code does not work. Can you please tell me why I can't use localbroadcast with pendingintent?

Thanks,

Currently my code stands:

boolean isCancelled;
Context context;

NotificationManager mNotifyManager;
NotificationCompat.Builder mBuilder;
int mId = 2;
protected void onHandleIntent(Intent intent) {
    isCancelled = false;
    context = getApplicationContext();
    IntentFilter filter = new IntentFilter();
    filter.addAction("com.migrationdesk.mylibman.MyServiceClass.STOP");
    registerReceiver(receiver, filter);
    getNotification();
    mainTask(); // THIS IS SOME BACKGROUND TASK
}

private final BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
                if(action.equals("com.migrationdesk.mylibman.MyServiceClass.STOP")){
                    isCancelled = true;
                }

    }
};

protected void getNotification() {
    Intent newintent = new Intent();
    newintent.setAction("com.migrationdesk.mylibman.MyServiceClass.STOP");
    PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, newintent, 0);
    mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    mBuilder = new NotificationCompat.Builder(context);
    mBuilder.setContentTitle("Cover Download")
                .setContentText("In progress")
                .setContentIntent(pIntent)
                .setSmallIcon(R.drawable.ic_launcher);
}
1

There are 1 answers

0
CommonsWare On BEST ANSWER

However, I was thinking is it possible to do the same with localBroadcast.

That is not possible. A PendingIntent only works with regular broadcasts, and the code that manages the notification bar is not in your process anyway.