一分钟周期服务 [英] One-minute periodic service
问题描述
什么是定期进行任务的正确方法是什么?
我的实现似乎并不正常工作:当屏幕上,我现在用的服务方法是完全及时跑了电话。然而,当手机被锁定的服务在非常大的随机时间间隔运行(例如:10:30 10:32 10:45 10:46 10:49 11:00 ......)
这里是code:
主要服务类:
@覆盖
公共无效的onCreate(){
PM =(电源管理)getSystemService(Context.POWER_SERVICE);
MNM =(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//显示关于我们开始通知。我们把在状态栏中的图标。
showNotification();
mHandler.postDelayed(periodicTask,ONE_MINUTE);
}私人处理程序mHandler =新的处理程序();
私有静态最终诠释ONE_MINUTE = 60000;私人Runnable接口periodicTask =新的Runnable(){ 公共无效的run(){
尝试{
激活锁定= pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,我的标签);
wakelock.acquire();
Log.v(PeriodicTimerService,醒);
的GetValues();
writeDB();
WRITELOG();
mHandler.postDelayed(periodicTask,ONE_MINUTE);
}
最后{
wakelock.release();
}
}
};
如果您需要周期性任务的方式运行即使手机处于睡眠状态,那么你别无选择每一分钟:必须使用AlarmManager。
What's the correct way to perform a periodic task? My implementation does not seem to work properly: when the screen is on and I am using the phone the service method is ran perfectly in time. However when the phone is locked the service is ran at very large and random intervals (e.g: 10:30 10:32 10:45 10:46 10:49 11:00...) Here is the code:
MAIN SERVICE CLASS:
@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();
}
}
};
If you need the periodic task to run exactly every minute even while the phone is sleeping then you have no choice: You must use the AlarmManager.
这篇关于一分钟周期服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!