点击通知按钮时,BroadcastReceiver未被调用。

3
在我的Service的onCreate方法中,我通过以下步骤创建通知:
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 已在我的清单中注册,如下所示(在看到这个问题后,我做了以下操作):
<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");
    }
}

通知已经显示出来,按钮也出现了,但是当我点击按钮时没有任何反应。

我不确定我做错了什么。非常感谢你提供的任何帮助。


可能会检查日志,以确定接收器的onReceive()方法是否被调用。 - Kalpesh Kulye
同时使用完整的包名注册 _.AlarmReceiver_。 - Piyush
@Piyush 我已经改成完整的包名了,但它仍然没有被调用。 - ClassA
1
@KalpeshKulye https://dev59.com/UVsV5IYBdhLWcg3w6iV8 - ClassA
1
可能是 https://dev59.com/fFYO5IYBdhLWcg3wU_6M 的重复问题。 - Ashok Kumar
显示剩余5条评论
1个回答

0

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

FLAG_UPDATE_CURRENT

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

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

例如:

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

你在清单文件中声明了这个服务吗?


尝试在切换到getForegroundService后重新启动设备。 - JakeB
我重新启动了设备,尝试将 Intent myIntent = new Intent("alarmReceiver"); 更改为 Intent myIntent = new Intent(this, AlarmReceiver.class); ,并且是在我的清单中声明的,否则通知甚至不会显示。 - ClassA
如果你能够贴出所涉及的全部类,那么调试起来会更加容易。 - JakeB
1
我找到了问题,今天晚些时候我会提供一个答案。感谢您抽出时间提供答案。 - ClassA

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接