Search code examples
androidtimerhandlerdelaysleep

Android handler as a timer not accurate


I'm using Handler to send message every 10 seconds. The problem occurs when I turn off the screen (device goes to sleep mode). Messages are sent every 30 sec - 2 mins instead of every 10 seconds. Why is this happening? How to resolve this problem?

public void PingTask() {        
    handler = new Handler();        
    runnable = new Runnable() {
        @Override
        public void run() {
            try {
                sendMSG("ping");
            } catch (Exception e) {}
            handler.postDelayed(this, 10000);
        }
    };
    runnable.run();
}

PingTask() is called from AsyncTask - onPostExecute().


Solution

  • Android is turning off your CPU. Use WakeLock to prevent your device from turning into some kind of sleep mode.

    You could also use an alarmmanager to send a message every second. An Alarm manager automatically prevents your device from turning into sleep mode.