Reputation: 1034
In my app I have a background service, this service starts a thread to do a periodic operation (I/O operation that cannot run on UI Thread), the thread code looks like this:
while(!stop){
do_io_things();
Thread.sleep(5000);
print_log();
}
I have noticed that when the device goes to sleep mode the thread sleeps for more than 5 seconds, sometimes it sleeps for a minute or so, but when the device is awake (even when my app is in background) the thread works as expected. I can check this by observing the log.
AFAIK sleep method should commit to the time it is passed to it, does any body know what is going on? does Android system extend the sleep time when the device is in sleep mode?
any help is appreciated.
Edit:
I tried to check more than one device, actually on newer devices the problem seems to be less effective as the change of time is not that big, on older devices running Kitkat 4.4 the change of sleep time is significant.
Upvotes: 0
Views: 311
Reputation: 27211
If you want to read about battery optimization, read this post:
https://developer.android.com/training/monitoring-device-state/doze-standby.html
In breaf, android devices fall asleep after several seconds. Some vendors kill all processes even you try to wake up by using foreground tasks.
The solutions:
am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE); am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nexttime, pi);
PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, APPNAME + Integer.toString(index)); if (wakeLock.isHeld()){ wakeLock.acquire(); }
Nonetheless, the second solution is killed by all of modern devices.
Upvotes: 2