执行周期性任务的正确方法是什么?我的实现似乎无法正常工作:当屏幕打开并且我正在使用电话时,服务方法会及时完美地运行。但是,当手机被锁定时,服务会以非常大的随机间隔运行(例如:10:30 10:32 10:45 10:46 10:49 11:00...)这是代码:
主要服务类别:
@Override
public void onCreate() {
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting. We put an icon in the status bar.
showNotification();
mHandler.postDelayed(periodicTask, ONE_MINUTE);
}
private Handler mHandler = new Handler();
private static final int ONE_MINUTE = 60000;
private Runnable periodicTask = new Runnable() {
public void run() {
try{
wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wakelock.acquire();
Log.v("PeriodicTimerService","Awake");
getValues();
writeDB();
writeLog();
mHandler.postDelayed(periodicTask, ONE_MINUTE);
}
finally{
wakelock.release();
}
}
};