从通知操作发送本地广播是否可行?

5

当在通知中点击按钮时,我想发送一条本地广播。我知道如何使用常规广播来实现这一点,但是我希望将广播保留在我的应用程序内。这可行吗?

我大致的代码如下:

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
2个回答

6
首先,LocalBroadcastManager是支持包的一部分(一个您可以添加到应用程序中的可选库),而不是系统本身的一部分。
其次,即使它是系统的一部分,通知服务也被所有应用程序使用。由于它是一个共享资源,当您发布通知时,没有任何“本地”发生的事情。

1
谢谢,那很有道理。 - Uli

1

这可能有效(对我有效)

将您的BroadcastReceiver添加到manifest.xml中

        <!-- If this receiver listens for broadcasts sent from the system or from
         other apps, even other apps that you own, set android:exported to "true". -->
    <receiver android:name=".myBroadcastReceiver" android:exported="false">
        <intent-filter>
            <action android:name="some" />
        </intent-filter>
    </receiver>

创建一个通知并添加操作(.addaction()),然后发送广播到BroadcastReceiver(你可以使用辅助函数)。
     Intent Rintent = new Intent(this , YOUR_BroadcastReceiver_CLASS.class );

  PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
  notificationIntent, 0);
  createNotificationChannel(ChanelID ,"name " , "Desc" );
  startForeground(FLAG_FORGRANDONLLINE, new NotificationCompat.Builder(ServiceFindTask.this,
  NotifID) // don't forget create a notification channel first
  .setOngoing(true)
  .setSmallIcon(R.mipmap.somet)
  .setContentTitle(getString(R.string.app_name))
  .setContentText("Service is running ")
  .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
  .setVibrate(new long[]{1000,100})
  .setContentIntent(pendingIntent)
  .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
  .setCustomContentView(notificationLayout)

  // Sending a action for BroadcastReceiver class
  .addAction(R.drawable.body,"GO offline" , makePendingIntent(SERVICE_TO_CLIENT_GO_OFFLINE , null , Rintent))
  .build());

   // Helper function

    public PendingIntent makePendingIntent(Integer action , @Nullable String data ,Intent intent) {
    intent.setAction( action.toString());
    if(data != null){
    intent.putExtra("kay", data);}
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    return pendingIntent;
 }

接收操作并使用LocalBroadcastManager创建本地广播,基于您的通知操作

public class myBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      switch (Integer.parseInt(action)){
        case Service.SERVICE_TO_CLIENT_GO_OFFLINE:
          helpLocalBroadcastManager(intent , context , Service.SERVICE_TO_CLIENT_GO_OFFLINE , null);
          break;
  
      }
  
    }
    private void helpLocalBroadcastManager(Intent intent ,Context context ,Integer action , @Nullable String data ) {
  
  
       intent = new Intent(action.toString());
      // Adding some data
      if(data != null){
        intent.putExtra("kay", data);}
      LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    
  }

现在您可以像这样在任何连接到BroadcastReceiver的活动中接收LocalBroadcast:
   private BroadcastReceiver messageReceiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
     String action = intent.getAction();
     switch (Integer.parseInt(action)){
       case Service.SERVICE_TO_CLIENT_GO_OFFLINE:
         Toast.makeText(Activity_Main.this , "This is massage from Activity_Main " , Toast.LENGTH_SHORT).show();
         break;
         }
 }
};
   @Override
 public void onResume() {
   super.onResume();
   LocalBroadcastManager.getInstance(this)
     .registerReceiver(messageReceiver, new IntentFilter(String.valueOf(ServiceFindTask.SERVICE_TO_CLIENT_GO_OFFLINE)));
}

这个问题是8年前的,但现在我需要它,这就是我做的,谢谢阅读。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接