Reputation: 3791
I have an android service that pulls updates from a server every 5 minutes. It works great when the screen is on, but when it is off it seems to pause. Keep in mind the service runs in the foreground using start foreground().
I am currently creating a new Thread and having it sleep in order to run the update every 5 minutes, is there a better method that would allow the timer to still run while the device is sleeping?
Upvotes: 0
Views: 2153
Reputation: 93559
Use an alarm via AlarmManager. The alarm will wake the CPU, allowing you to do your processing. If you're just waiting on a sleep in a thread, you won't be waken if the phone is off (its in sleep mode).
Of course you'll need a background thread or task to do the actual downloading. That's where a wakelock comes in. When the alarm goes off, request a wakelock. When you're done checking/downloading, release it. For your case, you can keep the same architecture- just instead of a 5 minute sleep waiting to recheck, wait on a semaphore. When the alarm comes in, request a wakelock and signal the semaphore. When the check is done, release the wakelock and semaphore, then wait on it again.
Upvotes: 1
Reputation: 344
The update isn't happening because the phone is going to sleep when you turn off the screen. Happens more often on WiFi if "Optimized WiFi" mode is turned on.
You should have a look at wakelocks. Acquire a wakelock to prevent device from falling asleep. Release it to let it sleep again. Note that this obviously increases battery consumption.
Upvotes: 1