[英]AlarmManager running at the wrong time
我试图让AlarmManager每隔3分钟运行一次,但它运行的时间错误且不同,时间以秒为单位,其他时间不运行。 我试图在Android 7.0和另一个6.0设备上测试并且两者都运行错误,我看到以下注释但无法修复。
警报管理器示例 AlarmManager在错误的时间触发警报 Android AlarmManager在错误的时间触发
以下代码:
long repeatTime = 180000;
AlarmManager processTimer = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intentAlarm = new Intent(context, TimerProcessReceiver.class);
PendingIntent pendingIntentAlarm = PendingIntent.getBroadcast(context, 0,
intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT);
if (android.os.Build.VERSION.SDK_INT < 19) {
processTimer.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
repeatTime, pendingIntentAlarm);
} else {
processTimer.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() +
repeatTime, pendingIntentAlarm);
}
仍然有问题,我已经更新如上。 更新为@ Vyacheslav的回复
long repeatTime = 180000 + System.currentTimeMillis();
AlarmManager processTimer = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intentAlarm = new Intent(context, ProcessReceiver.class);
PendingIntent pendingIntentAlarm = PendingIntent.getBroadcast(context, 0,
intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT);
int currentapiVersion = Build.VERSION.SDK_INT;
if (Build.VERSION.SDK_INT >= 23) {
processTimer.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
repeatTime, pendingIntentAlarm);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
processTimer.setExact(AlarmManager.RTC_WAKEUP,
repeatTime, pendingIntentAlarm);
} else if (currentapiVersion < Build.VERSION_CODES.KITKAT) {
processTimer.set(AlarmManager.RTC_WAKEUP, repeatTime,
pendingIntentAlarm);
}
如果我使用两个同时定时器与ids 0和1的PendingIntent(但添加这些PendingIntent的结构与上面的代码相同),但运行时间相同,为3分钟。 两者都在几秒钟内随机执行错误的方式。
请改用setExactAndAllowWhileIdle(int type, long triggerAtMillis, PendingIntent operation)
。 它有助于唤醒您的设备。
编辑
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion < android.os.Build.VERSION_CODES.KITKAT){
am.set(AlarmManager.RTC_WAKEUP, nexttime, pi);
} else {
if (currentapiVersion < android.os.Build.VERSION_CODES.M) {
am.setExact(AlarmManager.RTC_WAKEUP, nexttime, pi);
} else {
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nexttime, pi);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.