gpt4 book ai didi

java - 按下通知按钮时未调用 BroadcastReceiver

转载 作者:太空狗 更新时间:2023-10-29 14:35:14 25 4
gpt4 key购买 nike

在我的 ServiceonCreate 方法中,我通过执行以下操作创建通知:

String channelId = "001";
String channelName = "myChannel";

NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE);
channel.setLightColor(Color.BLUE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

if (manager != null) {
manager.createNotificationChannel(channel);
Notification notification;

Intent myIntent = new Intent("alarmReceiver");

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0);

Notification.Action action = new Notification.Action.Builder(
Icon.createWithResource(this, R.drawable.ic_stop_black_24dp),
"action string",
pendingIntent).build();


//Modify notification badge
notification = new Notification.Builder(getApplicationContext(), channelId).setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setCategory(Notification.CATEGORY_SERVICE)
.addAction(action)
.build();

startForeground(101, notification);
}

上面Intent中的alarmReceiver在我的manifest中注册如下(看到this问题后做了如下操作):

<receiver android:name=".AlarmReceiver">
<intent-filter>
<action android:name="alarmReceiver" />
</intent-filter>
</receiver>

这是我的 AlarmReceiver 类:

public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Log.e("onReceive - ","was called");
}
}

显示了通知和按钮,但是当我按下按钮时没有任何反应。

我不确定我做错了什么。任何帮助将不胜感激。

最佳答案

将 PendingIntent 设置为前台服务,并可能添加一个标志:

FLAG_UPDATE_CURRENT

PendingIntent pendingIntent = PendingIntent.getForegroundService(this, 0, myIntent, FLAG_UPDATE_CURRENT);

您的广播是隐式,因此如果您想使用getBroadcast(),最好显式通过提供intent 与接收器的 componentName

例如:

intent.setComponent(new ComponentName("packagename","fully qualified class name"));

您是否在 list 中声明了该服务?

关于java - 按下通知按钮时未调用 BroadcastReceiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57460700/

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