What is the correct way to perform a periodic task? My implementation does not seem to work properly: when the screen is turned on and I use the phone, the service method works fine in time. However, when the phone is locked, the service works at very large and random intervals (for example: 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);
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();
}
}
};
source
share