I am trying to put an AlarmManager to run every 3 min but it is running at wrong and varied times, moments in seconds and others does not run. I am trying to test on an Android 7.0 and another 6.0 device and both are running wrong, I saw the following comments but could not fix.
Alarm Manager Example AlarmManager fires alarms at wrong time Android AlarmManager fire at wrong time
The following code:
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);
}
Still having problems, I've updated as above. Update as @Vyacheslav's reply
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);
}
In case I am using two simultaneous timers with the PendingIntent of ids 0 and 1 (but the structure of adding these PendingIntent are the same as the code above) but with the same runtime 3 min. Both are executing the wrong way in a few seconds and randomly.