views:

66

answers:

1

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 performing 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 ?

+3  A: 

That's what AlarmManager is for.

Peter Knego