Android Service stop working when android device is sleep

401 views Asked by At

I am working with an android service. I want the service run always even when device is sleep. But my service is stop when my device is sleep. this is my code

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
   isRunning = true;
    mythread = new Thread() {
        @Override
        public void run() {
            while (isRunning) {
                turnOnScreen(60000*3);
                //Download some information by android Volley request   
                downloadInfo();             
              try {
                    Thread.sleep(60000*2);
                } catch (InterruptedException e) {
                    isRunning = false;
                    e.printStackTrace();
                }
            }
        }
    };
    if (isRunning) {
        if (!mythread.isAlive()) {
            mythread.start();
        }
    }

    return START_REDELIVER_INTENT;
}

And turnOnScreen method is

    private void turnOnScreen(long milliSeconds){
    PowerManager mgr = (PowerManager)this.getSystemService(this.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
    wakeLock.acquire(milliSeconds);
    }

Please help anyone. Thanks in advance.

1

There are 1 answers

0
CommonsWare On

I want the service run always even when device is sleep

Your users may disagree with this. Certainly lots of users have complained about poor battery life, which is why Google and device manufacturers have taken steps to stop developers from doing things like this.

But my service is stop when my device is sleep

On Android 8.0+, your service will stop running after one minute. On Android 6.0+, your approach will not work once the device goes into Doze mode. Some manufacturers implemented similar restrictions prior to Android 6.0. Plus, if downloadInfo() takes longer than a minute, the device may fall asleep between wakelocks.