Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reliable repeating background task on android

Tags:

android

I'm trying to run a background task which runs every minute or so for an android application but I am struggling to ensure that the task actually runs every minute. I've tried a variety of approaches from using SystemClock.sleep() to the AlarmManager (both repeating alarm and a fixed alarm) but it seems that unless the device is charging any kind of repeating system has a variable repeat rate once the device is unplugged. Is there any way to run a stable consistently repeating service?

like image 925
Brother Logic Avatar asked Aug 31 '09 07:08

Brother Logic


2 Answers

Have you implemented Timer? It works very well for what I use it for, but then again I haven't worried about the precision at all. For all I know it may be varying a bit but I doubt it. It seems pretty consistent to me.

Edit: I am not liable for your responsible or irresponsible use of this facility ;)

like image 139
MattC Avatar answered Sep 29 '22 08:09

MattC


If you need to have a service that runs every minute, on the minute, you have two options:

  • Use AlarmManager.setRepeating(RTC_WAKEUP, ...). In this case, the phone will sleep, but the RTC inside the phone will wake it up every minute to handle the repeating event. This will work, but will not be terribly exact as a lot of things are happening after the phone wakes up so your code might not get execution time right away.

  • Obtain a WakeLock from PowerManager and use whatever you want to time your code (Timer, Handler, etc.). This forces the phone to never sleep, which means that it is most likely free to run your code almost exactly when you request.

Both approaches will definitely drain the battery of the phone fast. Normally, the phone can sleep for 4 or even 9 minutes between wakes, so waking up once per minute is a big change from that.

like image 33
Nakedible Avatar answered Sep 29 '22 09:09

Nakedible