【问题标题】:AlarmManager not waking up a BroadcastReceiver after the specified timeAlarmManager 在指定时间后未唤醒 BroadcastReceiver
【发布时间】:2021-04-22 13:13:50
【问题描述】:

我的通知运行良好。这些通知由服务创建。 当我试图在用户没有点击它 3 分钟时关闭通知时。我在这里https://stackoverflow.com/a/23874764 尝试了 Karakuri 的解决方案,但什么也没发生。警报不起作用,广播接收器没有被调用。

服务类中的报警管理器:

notificationManager.notify(notificationId, n);
//set up alarm
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(context, MyReceiver.class);                                        intent.setAction("com.example.example.action.CANCEL_NOTIFICATION");
intent.putExtra("notification_id", notificationId);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP,180000,pi);

广播接收器onReceive方法:

public void onReceive(Context context, Intent intent) {
// do something
final String action = intent.getAction();
Log.d("Reciver","onReceive lunched");
if ("com.example.example.action.CANCEL_NOTIFICATION".equals(action)) {
int id = intent.getIntExtra("notification_id", -1);
if (id != -1) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
Log.d("Noti "+id," canceled ");
}}}

我之前没有和警报管理器打过交道。查了一下原因没找到,希望大家帮帮我

【问题讨论】:

    标签: java android notifications broadcastreceiver alarmmanager


    【解决方案1】:

    如果您需要在请求的时间准确触发,您应该使用alarmManager.setExactAndAllowWhileIdle 方法而不是alarmManager.set

    另外,你设置的时间错误。如果您想在当前时刻 3 分钟后触发警报,则必须是 System.currentTimeMillis() + 180000

    最后,检查您是否添加了SET_ALARM 权限并在AndroidManifest.xml 中声明了您的广播接收器。

    【讨论】:

    • 我按照您的指示进行操作,但问题仍然存在 :(
    【解决方案2】:

    您可以使用 Handler,它比使用 Alarm Manager 更容易。 由于您在 Service 中工作,请使用 Looper

    这里已经接受的答案将指导您:

    Clearing notification after a few seconds

    Using Handler inside service

    希望能帮到你!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多