【问题标题】:BroadcastReceiver not being called when pressing Notification Button按下通知按钮时未调用广播接收器
【发布时间】:2019-08-12 11:52:53
【问题描述】:

在我的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");
    }
}

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

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

【问题讨论】:

标签: java android android-service android-notifications


【解决方案1】:

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

FLAG_UPDATE_CURRENT

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

你的广播是Implicit,所以如果你想使用getBroadcast(),最好是Explicitly通过提供接收者的componentName来声明接收者。

例如:

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

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

【讨论】:

  • 切换到getForegroundService后尝试重启设备
  • 我重新启动了设备,我也尝试更改Intent myIntent = new Intent("alarmReceiver"); Intent myIntent = new Intent(this, AlarmReceiver.class);,是的,它已在我的清单中声明,否则通知甚至不会显示。
  • 如果您可以发布所涉及的整个类可能更容易调试
  • 我发现了这个问题,我将在今天晚些时候提供答案。感谢您抽出宝贵时间提供答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-26
  • 1970-01-01
相关资源
最近更新 更多