【问题标题】:AlarmManager occasionally doesn't fire alarmAlarmManager 偶尔不会发出警报
【发布时间】:2011-12-09 13:02:28
【问题描述】:

我正在为 Android 开发动态壁纸。要在设定的时间刷新壁纸,我使用 AlarmManager。大多数时候这很好用,但偶尔我的警报没有收到。最重要的是,我无法复制这种行为,它只是随机发生的。我使用至少 3 个 ROM 遇到过这个问题。

现在是代码。
我使用这个 PendingIntent:

mRefreshIntent = new Intent()
    .setComponent(new ComponentName(mContext, RefreshBroadcastReceiver.class))
    .setAction("my.package.name.REFRESH_WALLPAPER");
mPendingRefreshIntent = PendingIntent.getBroadcast(
    mContext, 
    0, 
    mRefreshIntent, 
    PendingIntent.FLAG_CANCEL_CURRENT);

这是我设置闹钟的代码:

mAlarmManager.set(AlarmManager.RTC_WAKEUP, time, mPendingRefreshIntent);

其中 time 是以毫秒为单位的 UTC 时间。我经常使用adb shell dumpsys alarm 验证警报是否按预期设置,确实如此。

接收方:

public class RefreshBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("DayNight", "onReceive     ; " + System.currentTimeMillis());
        DayNightService.refresher.refresh();
        Log.d("DayNight", "onReceive done; " + System.currentTimeMillis());
    }
}

相关清单行:

<application>
    ...
    <receiver
        android:name="RefreshBroadcastReceiver">
        <intent-filter>
            <action android:name="my.package.name.REFRESH_WALLPAPER" />
        </intent-filter>
    </receiver>
    ...
</application>

未触发的警报总是事先存在于队列中(dumpsys 警报),之后不在警报日志中。似乎他们在 T 减零时“迷路”了。

如果你们能帮我解决这个问题,我会很高兴。

【问题讨论】:

  • 你是否使用广播接收器类?
  • 是的,看第三个代码块。
  • 如果我取消现有的闹钟并用新的时间重新创建它,同样的事情也会发生在我身上。它显示在 adb 上,剩余正确的时间,但一旦达到 0,什么都没有发生。
  • 我想这是 AlarmManager 中的一个错误。我有一个类似的问题,很久以前安排的警报不知何故被遗忘了。如果我在重新启动后捕获启动完整意图并重新安排,也会发生这种情况。
  • 找到原因了吗?我也遇到了同样的问题。

标签: android alarmmanager android-alarms


【解决方案1】:

我使用以下代码:

  Intent intent = new Intent(ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_NO_CREATE);
    Log.d(LOG_TAG, "pending intent: " + pendingIntent);
    // if no intent there, schedule it ASAP
    if (pendingIntent == null) {
        pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        // schedule new alarm in 15 minutes
        alarmService.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(),300000, pendingIntent);
        Log.d(LOG_TAG, "scheduled intent: " + pendingIntent);
    }

请注意,我要求不准确的重复警报和 RTC(不是 RTC_WAKEUP) - 如果手机在牛仔裤口袋深处睡觉,用户对动态壁纸的更改不感兴趣 - 无需浪费电池电量并唤醒手机

您可能还需要注册启动完成广播接收器以开始更新调度 重启时。

【讨论】:

  • 这并不是我真正想要的:每次刷新间隔都不同,我(还)不担心电池寿命(如果我是的话,我可以用 RTC 替换 RTC_WAKEUP)。也许您可以指出我的代码中到底哪里有错误或 AlarmManager 中的错误?
  • 你在哪里激活这个意图?
  • WallpaperService.WallpeperEngine.onCreate() 中的第一个。触发前一个警报时设置下一个警报,依此类推。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多