gpt4 book ai didi

android - 如何从 AlarmManager 取消警报

转载 作者:IT老高 更新时间:2023-10-28 23:08:36 26 4
gpt4 key购买 nike

我也遇到过类似的问题。 Delete alarm from AlarmManager using cancel() - Android

"我正在尝试以两种不同的方法创建和删除警报,这两种方法都在应用程序的不同时刻调用。逻辑。

但是,当我调用 AlarmManager 的 cancel() 方法时,警报并没有被删除。"

为了设置:

            Intent myIntent = new Intent(getApplicationContext(),
SessionReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 1, myIntent, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

alarmManager.set(AlarmManager.RTC, now.getTimeInMillis(),
pendingIntent);

为了删除:

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent myIntent = new Intent(getApplicationContext(),
SessionReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

alarmManager.cancel(pendingIntent);

但这不会删除已注册的警报。提前致谢。

最佳答案

PendingIntent 需要完全按照启动 AlarmManager 时的方式创建,看起来主要问题是您使用了不同的 requestCode(零而不是一)。

为了快速修复,这应该可以:

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent myIntent = new Intent(getApplicationContext(), SessionReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 1, myIntent, 0);

alarmManager.cancel(pendingIntent);

为了使用 PendingIntent.FLAG_UPDATE_CURRENT 标志,见下文:

设置:

Intent myIntent = new Intent(getApplicationContext(), SessionReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 1, myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

alarmManager.set(AlarmManager.RTC, now.getTimeInMillis(), pendingIntent);

取消:

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent myIntent = new Intent(getApplicationContext(), SessionReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 1, myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);

alarmManager.cancel(pendingIntent);

关于android - 如何从 AlarmManager 取消警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28922521/

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