【发布时间】:2017-05-31 23:49:22
【问题描述】:
我试图让 AlarmManager 每 3 分钟运行一次,但它在错误和不同的时间运行,以秒为单位的时刻和其他不运行。我正在尝试在 Android 7.0 和另一台 6.0 设备上进行测试,但两者都运行错误,我看到了以下 cmets 但无法修复。
Alarm Manager Example AlarmManager fires alarms at wrong time Android AlarmManager fire at wrong time
以下代码:
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);
}
如果我同时使用两个计时器,其 PendingIntent 的 ID 为 0 和 1(但添加这些 PendingIntent 的结构与上面的代码相同),但运行时间相同 3 分钟。两者都在几秒钟内随机执行错误的方式。
【问题讨论】:
-
尝试记录这个 System.currentTimeMillis() + repeatTime 并在此处验证时间epochconverter.com
-
也粘贴 TimerProcessReceiver.class
-
@xbadal TimerProcessReceiver.class 只是一个通信 REST。
标签: android timer alarmmanager