One minute periodic service

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);
    // 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();
        }
    }
};
+3
source share
1 answer

If you need a periodic task to run exactly every minute, even when the phone is sleeping, you have no choice: you should use AlarmManager.

0
source

All Articles