I need to wake up a service every 60 seconds (for example).
The service configures itself to wake up with the following code:
private void rescheduleService() {
// setup calendar
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.SECOND, 60);
// setup intent
Intent serviceGeofence = new Intent(this, ServiceGeofence.class); // this service
PendingIntent pendingIntent = PendingIntent.getService(this, 0, serviceGeofence, PendingIntent.FLAG_CANCEL_CURRENT);
// setup alarm
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
if(Build.VERSION.SDK_INT >= 23) {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
pendingIntent);
} else if(Build.VERSION.SDK_INT >= 19){
alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
pendingIntent);
} else {
alarmManager.set(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
pendingIntent);
}
Log.i(TAG, "next alarm: " + calendar.toString());
Log.i(TAG, "alarm configured");
}
The code above works fine while the phone is charging or connected via USB. It executes every 60 seconds as expect. And I able to see it in LogCat.
BUT, when I unplug phone from USB, the service is wake up randomly (3 or 5 minutes,... even 30 minutes later).
I'm using methods like setExactAndAllowWhileIdle
, setExact
(it depends of Android version) to wake up the device extrictly in the time I configured it. But it only works when device is connected to USB.
TL;DR; With code above:
- When device is connected to USB: works fine.
- When device is disconnected from USB: doesnt work as expected.
Any idea of what is happening?