gpt4 book ai didi

android - AlarmManager 没有按时触发

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:01:41 25 4
gpt4 key购买 nike

我希望根据用户移动设备时间在每天上午 10:30 触发 AlarmManager。它肯定会在上午 10:30 触发,但问题是在上午 10:30 之后,它会无时间重复,例如每半小时之后或任何不寻常的时间间隔之后。

如何预防这个问题?我在成功登录和注册 ButtonCick() 事件中调用它。如果用户注销,我也想停止此操作。

我的代码如下:

        Intent myIntent = new Intent(Register.this, AlarmReceiver.class);

PendingIntent pendingIntent = PendingIntent.getBroadcast(Register.this,
0, myIntent, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

Calendar firingCal = Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();

firingCal.set(Calendar.HOUR_OF_DAY, 10);
firingCal.set(Calendar.MINUTE, 30);
firingCal.set(Calendar.SECOND, 0);

long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();

if (intendedTime >= currentTime) {

WakeLocker.acquire(getApplicationContext());

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, intendedTime,
AlarmManager.INTERVAL_DAY, pendingIntent);

WakeLocker.release();

} else {

WakeLocker.acquire(getApplicationContext());

firingCal.add(Calendar.DAY_OF_MONTH, 1);
intendedTime = firingCal.getTimeInMillis();

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, intendedTime,
AlarmManager.INTERVAL_DAY, pendingIntent);

WakeLocker.release();
}

最佳答案

代码看起来不错。如果目标版本是19,

注意:

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.

来源: http://developer.android.com/reference/android/app/AlarmManager.html#setRepeating(int,long,long,android.app.PendingIntent)

注意:

Beginning in API 19, the trigger time passed to this method is treated as inexact: the alarm will not be delivered before this time, but may be deferred and delivered some time later. The OS will use this policy in order to "batch" alarms together across the entire system, minimizing the number of times the device needs to "wake up" and minimizing battery use. In general, alarms scheduled in the near future will not be deferred as long as alarms scheduled far in the future.

使用新的批处理政策后,交货订单保证不如以前那么可靠。如果应用程序设置了多个警报,则这些警报的实际交付顺序可能与其请求的交付时间顺序不匹配。如果您的应用程序有强烈的排序要求,您可以使用其他 API 来获得必要的行为;参见 setWindow(int, long, long, PendingIntent) 和 setExact(int, long, PendingIntent)。

targetSdkVersion 在 API 19 之前的应用程序将继续获得以前的警报行为:所有计划的警报都将被视为准确的。

来源: http://developer.android.com/reference/android/app/AlarmManager.html#set(int,long,android.app.PendingIntent)

请检查这是否符合您的要求。

关于android - AlarmManager 没有按时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21642423/

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