gpt4 book ai didi

Android 重复闹钟没有正确重复

转载 作者:行者123 更新时间:2023-11-29 14:37:13 25 4
gpt4 key购买 nike

我有一个闹钟,我想大约每 5 分钟重复一次。出于测试目的,我将其设置为每 5 重复一次,如下所示:

AlarmManager alarmManager = (AlarmManager)getActivity().getSystemService(getActivity().ALARM_SERVICE);
Intent intent = new Intent(getActivity(), CoordinateAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getService(getActivity(), 1, intent, 0);
int repeatSeconds = 5;
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
repeatSeconds * 1000, pendingIntent);

并且接收 IntentService 在收到警报时会打印一条日志语句。但是,它大约每分半钟触发一次,而不是每 5 秒一次,它在哪里设置不正确?我也尝试过使用 setRepeating() 而不是 setInexactRepeating() 但我得到了相同的结果。

这是我的闹钟接收器:

public class CoordinateAlarmReceiver extends IntentService {

public CoordinateAlarmReceiver(){
super("CoordinateAlarmReceiver");
}

/*
Alarm received, get new contacts which then shows notification
*/
@Override
protected void onHandleIntent(Intent intent) {
MyLog.i("coordinate alarm received");

//new GetNewContactsTask(this).execute();
}
}

最佳答案

我假设您使用的是 api 19 或更高版本。 alarmmanager 文档说:

Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.

您尝试使用 setRepeating(),但在 api 19 及更高版本上调用 setInexactRepeating()。 19岁以上的你

setInexactRepeating(): Schedule a repeating alarm that has inexact trigger time requirements; for example, an alarm that repeats every hour, but not necessarily at the top of every hour.

这解释了你奇怪的结果。

如果你想设置在一个excat时间,你应该使用setExact。不幸的是没有 setExactRepating 所以你必须自己创建它。在一个执行或类似的事情之后安排一个新的警报。

alarmmanager 文档中的注释:

Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.

也许你应该看看这个。

关于Android 重复闹钟没有正确重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30812669/

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