问题描述
我实现了我的Android应用程序服务启动一个定时器(使用标准java.util.Timer中和java.util.TimerTask中的机制)做一些处理上pre定义的时间间隔背景。
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.
什么是执行该继续正常运行的定时器的正道,即使手机已经进入暂停。我应该诉诸使用电源管理和WAKE_LOCKS(如这里所描述),或者是有其他的机制
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 ?
推荐答案
这就是是。
这篇关于(即使在屏幕超时)实现在Android中的计时器是积极的所有时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!