gpt4 book ai didi

java - BroadcastReceiver.onReceive 未调用,但 Activity.onNewIntent 执行。为什么?

转载 作者:行者123 更新时间:2023-12-02 10:06:31 25 4
gpt4 key购买 nike

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

当 Intent 目标是Activity(点击Activity.onNewIntent)时,它效果很好,但使用它很奇怪,因为当消息被忽略时, Activity 会进入前台。

请帮助对 BroadcastReceiver 进行 onReceive 调用。它是可见的、导出的和启用的,位于同一个包中。

MyCancelReceiver 类

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

Android list

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

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

主要 Activity

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

提前谢谢您。

最佳答案

这是因为当您启动 Activity 时,onStart() 会被调用,一旦 Activity 启动,您就会在 onReceive() 中收到回调。但是,当您单击通知时,由于 Activity 已经创建,因此 onStart 将不会被调用,在这种情况下, onStart 将不会被调用。尝试在 onResume() 中注册,我很确定它会起作用。

关于java - BroadcastReceiver.onReceive 未调用,但 Activity.onNewIntent 执行。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55304243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com