挂起的BroadCastReceiver无法启动setDeleteIntnet

时间:2017-07-06 05:43:11

标签: android broadcastreceiver android-notifications android-pendingintent localbroadcastmanager

我发出通知,我想要做的是,当用户点击我发送的通知清除它时,我想要执行待处理的广播。 有一个名为'setDeleteIntent'的方法。根据此方法的文档,当用户清除收到的通知时,它应该启动待处理的BraodCast接收器.7

我在代码中创建了一个Broadcast Receiver类,如下所示,我提供了带有挂起广播的'setDeleteIntent'方法。 但是在运行时,当收到通知然后清除时,BroadcastReceiver的“onReceive”中的日志消息没有显示在控制台上!!

请看下面的代码,请让他们知道为什么broadcastReceiver的'onReceive'永远不会执行。

注意:BroadCasrReceiver使用'LocalBroadCastReceiver'注册,如代码所示。

    String title = getString(R.string.app_name);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher);
    builder.setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg).setContentTitle(title);
    builder.setContentIntent(contentIntent).setAutoCancel(true);

    //builder.setWhen(Long.valueOf(eu.man.m24wsapp.utils.gcm.TimeUtils.getNowTS()) + 5000);
    builder.setLights(Color.argb(1, 0, 0, 255), 1000, 400);
    builder.setOngoing(false);
    builder.setAutoCancel(true);


    builder.setDeleteIntent(getPendingBroadCast());
    ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFICATION_ID, builder.build());
    ....
    ....
    ....

    //getPendingBroadCast method
    private PendingIntent getPendingBroadCast() {
    LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(new BCRDismissNotification(),
            new IntentFilter(BCRDismissNotification.ACTION_DISMISSED_NOTIFICATION));

    Intent intent = new Intent(this, BCRDismissNotification.class);
    //intent.setAction(BCRDismissNotification.ACTION_DISMISSED_NOTIFICATION);
    return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}

BroadCast接收器

public class BCRDismissNotification extends BroadcastReceiver {
private final static String TAG = BCRDismissNotification.class.getSimpleName();
public final static String ACTION_DISMISSED_NOTIFICATION = "action_dismissed_notification";

@Override
public void onReceive(Context context, Intent intent) {

    Log.i(TAG, "*********************   BCR     **************");
}

}

1 个答案:

答案 0 :(得分:1)

你几乎回答了自己的问题。这不适用于LocalBroadcastManager

使用LocalBroadcastManager注册接收器时,它只会侦听应用程序广播的广播Intent。在您的情况下,广播Intent由Android的通知框架发送,该框架不属于您的应用程序。在这种情况下,您的注册接收器将不会被触发。

您需要注册接收器以进行全球广播。您可以通过创建接收器实例并在应用程序registerReceiver()上调用Context来执行此操作,也可以将接收器添加到带有<receiver>标记的清单中,并确保设置android:exported="true"