问题
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();
}
}
};
回答1:
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.
来源:https://stackoverflow.com/questions/10482583/one-minute-periodic-service