Search code examples
androidnotificationsbroadcastandroid-pendingintent

Is it possible to send a LocalBroadcast from a notification action?


I would like to send a LocalBroadcast when clicking on a button inside a notification. I know how to do that with a regular broadcast, but I would like to keep the broadcast inside my app. Is this possible?

The code I have is roughly:

NotificationCompat.Builder notificationBuilder  = new NotificationCompat.Builder(context)
    .setContentTitle("Title")
    .setContentText("content")
    .setSmallIcon(R.drawable.icon1)
    .setContentIntent(pIntent)
    .setAutoCancel(true);


Intent myButtonIntent = new Intent(BUTTON_PRESSED);

// the following line gives me a normal broadcast, not a LocalBroadcast
PendingIntent myButtonpIntent = PendingIntent.getBroadcast(context, 12345, myButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT);  
notificationBuilder.addAction(R.drawable.icon2, "OK", myButtonpIntent);
Notification notification = notificationBuilder.build();
NotificationManager notificationManager = 
    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

And also:

BroadcastReceiver bReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(BUTTON_PRESSED)) {
            // do something
        }
    }
};

LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BUTTON_PRESSED);
bManager.registerReceiver(bReceiver, intentFilter); // I want to use the LocalBroadcastManager
// registerReceiver(bReceiver, intentFilter);  // Instead, I have to use this line for a non-local broadcast

Solution

  • No.

    First of all, LocalBroadcastManager is part of the support package (an optional library you add to your application), not part of the system itself.

    Secondly, even if it were, the notification service is used by all applications. Since it's a shared resource, there is nothing "local" that occurs when you post a notification.