BroadcastReceiver.onReceive不会被调用,但是Activity.onNewIntent会被调用。为什么?

时间:2019-03-22 16:43:52

标签: java android notifications broadcastreceiver

我正在尝试从通知中获取“ DeleteIntent”回调。 未从PendengIntent调用 BroadcastReceiver.onReceive ,但是当使用 sendBroadcast(deleteIntent)手动启动广播时,它工作正常。

当意图目标为 Activity (命中 Activity.onNewIntent )时,效果很好,但是由于消息被取消时活动成为前台,因此使用它很奇怪。

请帮助 onReceive 致电 BroadcastReceiver 。 它位于同一程序包中可见,导出和启用。

MyCancelReceiver类

public class MyCancelReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
    }
}

Android清单

<activity android:name=".MainActivity" android:launchMode="singleTask">

<MyCancelReceiver" android:enabled="true" android:exported="true">
    <intent-filter>
        <action android:name="notification_cancelled"/>
    </intent-filter>
</receiver>

MainActivity

private MyCancelReceiver mReceiver;

@Override
public void onStart() {
    super.onStart();

    IntentFilter filter = new IntentFilter();
    filter.addAction("notification_cancelled");
    mReceiver = new MyCancelReceiver();
    registerReceiver(mReceiver, filter);
}

@Override
public void onStop() {
    super.onStop();       
    unregisterReceiver(mReceiver);
}

通知创建:

Intent cancelIntent = new Intent(getApplicationContext(), MyCancelReceiver.class);
cancelIntent.setAction("notification_cancelled");
cancelIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent deleteIntent = PendingIntent.getActivity(getApplicationContext(), 0, cancelIntent, PendingIntent.FLAG_CANCEL_CURRENT);

Notification not = new Notification.Builder(getApplicationContext(), Util.ANDROID_CHANNEL_ID)
        .setContentTitle(messageTitle)
        .setContentText(messageBody)
        .setSmallIcon(R.drawable.default)
        .setAutoCancel(true)
        .setDeleteIntent(deleteIntent)
        .setContentIntent(contentIntent)
        .build();

NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, not);

谢谢。

2 个答案:

答案 0 :(得分:0)

这是因为当您开始活动时,将调用onStart(),并且在活动启动后将在onReceive()中获得回调。但是,当您单击通知时,由于已经创建了活动,因此不会调用onStart,在这种情况下,不会调用onStart。尝试在onResume()中注册,我很确定它会起作用。

答案 1 :(得分:0)

使用此线程Click on android notification icon does not trigger broadcast receiver的答案解决了问题

将显式意图替换为隐式意图。     意向cancelIntent =新的Intent(“ notification_canceled”);