I'm at my wits end with this issue. Can't find a good solution for it! In my app I have a service within which a timer gets scheduled over and over. That means after each timerTask is executed, another is started (first, both the timer and timerTask are canceled and then are assigned a new Timer and TimerTask). This is done 24 hours a day! I need this: First launch the app, start the service, then turn off the display and leave the device alone. But trouble is every time I come back to the device, I find my app has finished some tasks then is stuck on a timer although its time interval is passed! I think this is because of CPU sleeping.
For more explanation, suppose I have a list of time intervals in seconds: {60,100,40,120,80}. I start the service and leave the device alone for 5 minutes. Then I come back and see that tasks at 60 and 100 secs are done. But the service is stuck at the task at 40!
Each task includes a very simple network job that takes 5 secs at most. I tried a wakelock but It's not gonna help. I don't know why!
Here is a code of my service:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(id, new Notification());
pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK,"");
wl.acquire();
doAction();
return START_STICKY;
}
private void doAction(){
if (timer != null)
timer.cancel;
if (timerTask != null)
timerTask.cancel;
timer = new Timer();
timerTask = new TimerTask() {
@Override
public void run() {
doAction();
//Do some network job!
}
};
timer.schedule(timerTask, getNewInterval());
}