调用取消后,Android AlarmService repeating alarm 重复一次

标签 android

首先,这个网站很棒,每个人都非常乐于助人。这是我的第一篇文章,如有遗漏请见谅。

我这样创建一个闹钟:

private void startLocation() {

    AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent i = new Intent(context, MyWeatherUpdateService.class);
    PendingIntent service = PendingIntent.getService(context, 0, i,
                PendingIntent.FLAG_CANCEL_CURRENT);

    alarm.setRepeating(AlarmManager.RTC, SystemClock.elapsedRealtime() + (60 * 1000),
            Long.parseLong(prefs.getString("listpref", "60000")), service);

}

在 fragment 内部调用的这个方法中,上下文来自getApplication(),listpref是一个字符串更新间隔,以毫秒为单位。

我通过以下方式取消:

public void endLocation() {

    Intent i = new Intent(context, MyWeatherUpdateService.class);
    PendingIntent service = PendingIntent.getService(context, 0, i,
                PendingIntent.FLAG_CANCEL_CURRENT);
    alarm.cancel(service);

}

确保 Intent/未决 Intent 相同。

现在我有两个问题:

1) 警报几乎在创建后立即触发,即使我告诉它在 1 分钟后启动。 2) 当我调用取消时,警报会在警报被取消前再次触发。

问题 1)为什么警报这么快就响了? 2) 这是按预期工作还是应该像我希望的那样立即取消警报。

如果我没有提供足够的信息,我会根据需要添加更多代码。

提前致谢。

最佳答案

the alarm fires almost imediately after creation, even though i tell it to start after 1min

那是因为您正在使用 RTCelapsedRealtime() 开始时间。那些需要匹配。最简单的解决方案是切换到 ELAPSED_REALTIME

when i call cancel, the alarm fires once more before the alarm is cancelled.

尝试将 PendingIntent.FLAG_CANCEL_CURRENT 替换为 0,至少在 cancel() 调用的 PendingIntent 中.

关于调用取消后,Android AlarmService repeating alarm 重复一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16780232/

相关文章:

android - onActivityResult 从未调用过

java - applyLinearImpulse 不起作用(Box2d)

android - MapView 没有从 ViewPager 中删除?

c# - CreateUserWithEmailAndPasswordAsync 错误 "Object reference not set to an instance of an object."

javascript - 输入文本控件在 Android 谷歌浏览器上不起作用

不同选项卡中的 Android WebView

android - 在不推荐使用的情况下强制 gradle 构建失败

android - Eclipse 是否适合 Android 开发?

android - Android Studio 上的实验性 NDK 支持

android - 每次手机休眠时定时器都会停止