是否可以从通知操作发送LocalBroadcast?

时间:2014-03-15 00:10:19

标签: android notifications broadcast android-pendingintent

我想在点击通知中的按钮时发送LocalBroadcast。我知道如何通过常规广播来做到这一点,但我想将广播保留在我的应用程序中。这可能吗?

我的代码大致是:

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);

还有:

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

1 个答案:

答案 0 :(得分:5)

没有

首先,LocalBroadcastManager是支持包(您添加到应用程序中的可选库)的一部分,而不是系统本身的一部分。

其次,即使是这样,通知服务也会被所有应用程序使用。由于它是一个共享资源,因此没有任何东西可以解决这个问题。发布通知时会发生这种情况。