android 定时器状态,在Android中实现一直处于活动状态的计时器(即使在屏幕超时期间)(Implementing a timer in Android that's active all t...

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 ?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值