简体   繁体   中英

Assured wakeup of AsyncTask after Thread.sleep

I have a foreground service, which creates an asynctask in its onCreate(). The asynctask has a while(true) in its doInBackground. In this function, it performs certain network operation and goes to sleep for a random interval after each iteration. Here is the logic:

doInBackground(){
     while(true){
         //Do network operation
         //randomNumber is a random number calculated each iteration and is in range of 60-180
         Thread.sleep(randomoNumber*1000);
     }

}

Now my issue is that as soon as the device goes to sleep, it sleeps the asynctask too. The network operation is highly critical in sticking to the time interval(randomNumber) and it can not be afforded that it be sleeping more than the randomNumber seconds(although difference of a few seconds can be tolerated). So how do I assure that the asynctask does wakes up after Thread.sleep, even when the device is not in active state? I think I can use a wakelock, but that may keep the task running forever as it has a while(true) loop and hence drain out the battery. If I use it before Thread.sleep and release it after the network operation, again the same issue of the task not waking after the thread.sleep may occur. So what can be done here?

You could force the CPU to be on even when the device sleeps see here http://developer.android.com/training/scheduling/wakelock.html#cpu as they say:

One legitimate case for using a wake lock might be a background service that needs to grab a wake lock to keep the CPU running to do work while the screen is off

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM