BroadcastReceiver.onReceive没有被调用,但Activity.onNewIntent做了。为什么?

问题描述 投票:0回答:2

我试图从我的通知中获取“DeleteIntent”回调。 BroadcastReceiver.onReceive没有从PendengIntent调用,而当使用sendBroadcast(deleteIntent)手动启动广播时它工作正常。

当目标目标是Activity(命中Activity.onNewIntent)时,它运行良好但是使用它很奇怪,因为当消息被解除时,活动变为前景。

请帮忙联系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>

主要信息

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

先感谢您。

java android notifications broadcastreceiver
2个回答
0
投票

这是因为当你开始你的活动时,onStart()会被调用,一旦活动启动你就会在onReceive()中得到一个回调。但是当你单击你的通知onStart将不会被调用因为已经创建了活动,在这种情况下,onStart将不会被调用。尝试注册onResume(),我很确定它会起作用。


0
投票

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

用隐式意图取代显式意图。 Intent cancelIntent = new Intent(“notification_canceled”);

© www.soinside.com 2019 - 2024. All rights reserved.