Search code examples
androidsleepthread-sleep

Android thread pause in standby


I'm trying to write a simple Activity with a thread that write a value in a text files every N seconds.

The problem is that after some minutes I've run the Activity, with the phone in standby, the thread sometime stops for a larger time, even minutes.

In the Run() I've to write the file than sleep for N seconds.

public void run() {
    isrunning = true;
int cont=0;
    try {
        while (isrunning)
        {
            es.writeSD("- THREAD:" + cont, true);
            Thread.sleep(1000);
            es.writeSD("- THREAD - sending: " + cont,true);             
            cont++;
        }
    } 
    catch (InterruptedException e) {
        es.writeSD("- THREAD - InterruptedException: " + e.getMessage(),true);
    }
    catch (Exception e) {
        es.scriviSD("- THREAD - Exception: " + e.getMessage(),true);
    }   
}

This is the log with the timestamp

20130911T154448 : - THREAD:36

20130911T154449 : - THREAD sending: 36

20130911T154449 : - THREAD:37

20130911T154652 : - THREAD sending: 37

20130911T154652 : - THREAD:38

20130911T154656 : - THREAD sending: 38


Solution

  • You need to force the device to stay awake. But be careful, this will drain battery very fast!

    PowerManager's WakeLock is what you need: https://developer.android.com/reference/android/os/PowerManager.WakeLock.html

    When starting the Thread, acquire() the WakeLock, release() it, when you are finished.

    public void run() {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
        wl.acquire();
        isrunning = true;
        int cont=0;
        try {
            while (isrunning) {
                es.writeSD("- THREAD:" + cont, true);
                Thread.sleep(1000);
                es.writeSD("- THREAD - sending: " + cont,true);             
                cont++;
            }
        } catch (InterruptedException e) {
            es.writeSD("- THREAD - InterruptedException: " + e.getMessage(),true);
        } catch (Exception e) {
            es.scriviSD("- THREAD - Exception: " + e.getMessage(),true);
        } finally {
            wl.release();
        }
    }