gpt4 book ai didi

android - AlarmManager 偶尔不触发警报

转载 作者:行者123 更新时间:2023-11-29 00:42:40 28 4
gpt4 key购买 nike

我正在为 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());
}
}

相关 list 行:

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

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

如果你们中有人能为我解决这个问题,我将非常高兴。

最佳答案

我使用以下代码:

  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)——如果手机在牛仔裤口袋深处 sleep ,用户对动态壁纸的变化不感兴趣——不需要浪费电池电量和唤醒手机

您可能还需要注册 boot complete broadcast receiver 来开始更新调度在重新启动。

关于android - AlarmManager 偶尔不触发警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8445867/

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