One-minute periodic service

爷,独闯天下 提交于 2019-12-07 17:43:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!