Reputation: 31
Hello to all Android developers, I wish to ask a question about something that drives me mad over the last few weeks and I cannot make it work properly.
I have an Android app that runs a service that has a loop in it that runs every few seconds and should run endlessly and never stop, not even if the screen is off. this service will run regardless of the app's UI being open or not. it runs even if the task stack was cleared.
I implemented all that by using a service and a TimerTask inside the service class, like this:
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
public void run() {
//Do something that will run again and again every time that the timer is called. every 10 seconds.
}
};
timer.schedule(timerTask, 1000, 10000);
I added a WakeLock inside this loop (And I also tried to run the WakeLock only once outside of the loop):
PowerManager mgr = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "myapp:MyWakeLock1234");
if (!wakeLock.isHeld()) {
wakeLock.acquire();
Log.d("WAKEWAKE", "WAKELOCK ACQUIRED NOW...");
}
I never release the WakeLock because the service loop runs infinitely even with the screen off.
Inside the timer's loop I also added a MediaPlayer sound that will beep every few seconds (For testing purposes - I intent to remove it if all works o.k):
MediaPlayer mp = MediaPlayer.create(MyService2.this, R.raw.beepbeep);
mp.setOnCompletionListener(MediaPlayer::release);
mp.start();
The service itself runs fine and I also set the app to reload the service after BOOT and it works fine also.
The only problem that I have is AFTER I switch the phone's screen off using the power button or whenever the screen switches off on any circumstance - and then the timer keeps on running and the beep keeps on playing for every 10 seconds and then... STOPS ! It may stop for few minutes, it may stop for 20 minutes, it will resume beeping when the screen is off (WakeLock) after that for 1 or more times and AGAIN. Stops for another N minutes.
Once I open the phone's display to go out of wakelock - the loop magically resume running every 10 seconds and beeping well like there is no problem ! I tried everything ! I tried to remove the MediaPlayer beeps, tried to run the WakeLock only once and not in a loop, tried to make a lousy loop instead of using a TimerTask. Everything works well until the screen turns off ! it looks like my service gets into some sort of sleep mode or pause. I even tried to download a piece of code from GitHub that claims to work well, but it stops/pauses exactly the same way ! I have to comment that the TimeTask is EMPTY at this point and runs nothing except from the WakeLock code and the MediaPlayer beep. No communication, no nothing !
What can I do about it to solve this problem ? Thank you for your kind answers ! I appreciate it !
Upvotes: 0
Views: 197