gpt4 book ai didi

java - AlarmManager 没有在每个时间间隔精确调用 BroadcastReceiver

转载 作者:行者123 更新时间:2023-12-01 10:22:18 26 4
gpt4 key购买 nike

我有以下BroadcastReceiver:

public class LocationUpdateReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
LocationHelper locationHelper = new LocationHelper(context);
locationHelper.updateLocation();

//.. do stuff with location

}

public static void SetAlarm(Context context, Long time){
Intent intentAlarm = new Intent(context, LocationUpdateReceiver.class);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getBroadcast(context, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), time, pi);
}

public static void CancelAlarm(Context context) {
Intent intent = new Intent(context, LocationUpdateReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}

我像这样调用 setAlarm 方法来从 Activity 进行测试:LocationUpdateReceiver.SetAlarm(this, 3000L);

您会注意到我调用了 setRepeating(),我认为它应该每 3 秒调用一次接收器类?

问题是,通常情况下,它不会调用接收者超过 5 分钟,这是一个相当大的偏差。我打算每 30 分钟运行一次接收器,但是我应该期望偏差时间的相对百分比吗?

如何确保它会按照我指定的时间间隔准确(或以非常小的偏差)调用?

最佳答案

来自 setRepeating() 的文档:

Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.

您可以使用setExact()并自行设置间隔。

关于java - AlarmManager 没有在每个时间间隔精确调用 BroadcastReceiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35505028/

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