Implementing a timer in Android that's active all the time (even during screen timeout)
I've implemented a Service in my android app that starts a timer (using the standard java.util.Timer and java.util.TimerTask mechanism) to do some processing in the background on a pre-defined interval.
public class BackgroundProcessingService extends Service {
private int interval;
private Timer timer = new Timer();
public void onCreate() {
super.onCreate();
startTimer();
}
@Override
public void onDestroy() {
timer.cancel();
super.onDestroy();
}
public int getInterval() {
return interval;
}
public void setInterval(int interval) {
this.interval = interval;
}
private void startTimer() {
timer.scheduleAtFixedRate( new TimerTask() {
public void run() {
// perform background processing
}
}, 0, getInterval());
; }
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
The service is started / stopped by my application like this.
backgroundProcessingService = new Intent(getApplicationContext(), BackgroundProcessingService .class);
startService(backgroundProcessingService);
As long as the phone is active (no screen-timeout occured), the service is running fine, and the Timer is perf开发者_运维百科orming its job at the defined interval. Even when I quit the application (using the back button), the timer remains active.
However, as soon as the phone goes into timeout, the timer task is no longer running stable. If I leave the phone in timeout for several hours (at night), I would see that on random occasions (sometimes a several hours interval) the timer kicked in.
Also, when the phone is activated again, all timer runs that have been queued are suddenly executed in one shot before resuming back to the normal interval.
What would be the right way of implementing a timer that continues to run properly, even after the phone has gone into timeout. Should I resort to using the PowerManager and WAKE_LOCKS (as described here http://code.google.com/android/reference/android/os/PowerManager.html), or is there another mechanism ?
That's what AlarmManager is for.
Kind of pointless to put another answer up here, but will for philosophical reasons.
AlarmManager is for sure not the answer here, but then, neither is Handler. You do a Handler when you are concerned about have runnables that can then act on a Thread other than the one you are running on (as described in this answer Updating GUI: Runnables vs Messages).
The real answer is that if you have a reason to time something in your own app, that means that there are probably domain events that you need to incorporate into whatever your model is, so for instance, if I am going to be sending emails, I would have some events about email states/transformations. This is what Reactive Programming is: pulling the process of responding to things up into the design level of the software, not just treating scheduling as a boiler room detail that's stashed under a layer of 'objects.'
精彩评论