在使用AlarmManager的cancel()方法取消定时任务时,需要保证PendingIntent参数与设置定时任务时使用的PendingIntent一致。
例如,对于以下的设定:
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
long triggerAtTime = System.currentTimeMillis() + DELAY_TIME;
alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtTime, pendingIntent);
想要取消掉该定时任务,则需要在Intent、PendingIntent、AlarmManager的参数设置与上述代码相同的前提下调用cancel()方法:
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
这样,通过保证Intent和PendingIntent一致,就能成功取消掉之前设定的定时任务。
上一篇:AndroidAlarmManager插件中的“setAlarmClock()存在Doze模式问题”
下一篇:AndroidAlarmManager调用flutterLocalNotificationsPlugin.show(),但没有显示通知。