I have a service that uses wakelocks to keep the screen on. Everything works wonderfully while the service is running: I am able to acquire and release the wakelock depending on different functions.
However, when the user turns off the service, I release the wakelock in onDestroy. Although I am calling wakelock.release() , and the service ends, the wakelock continues until the process is killed. I can see that onDestroy has been called with the log, as well as the second log call. What am I doing wrong?
@Override
public void onDestroy() {
releaseMainWakeLock();
Log.d(TAG, "ScreenService destroyed");
}
private static void releaseMainWakeLock() {
if(wakeLockMain.isHeld()) {
Log.d(TAG, "Wakelock being released!");
wakeLockMain.release();
}
}
UPDATE: It looks like NO code is actually successful in onDestroy, even though onDestroy does run (as can be seen by the log call). For example, I have some receivers that are supposed to be unregistered in onDestroy. onDestroy runs, the service is "killed" but remains as a cached background process that continues to do functions of the running service!
Each time I stop and start the service, there is a new set of listeners being registered and never unregistered. For example, I have a proximity listener that logs "Proximity event". After I start and stop the service 3 times, looking at logcat after placing my hand over the proximity sensor shows:
"Proximity event Proximity event Proximity event"
This is even though the service should have stopped and that sensor listener should have been unregistered in onDestroy!
I figured it out. I had a runnable thread that re-triggered itself every 5 seconds. Since this runnable was not stopped, it was re-registering the proximity sensor and re-acquiring the wakelocks even after onDestroy released the sensor and released the wakelocks!
Lesson to be learned: Be careful, code of the service does not stop with onDestroy and will keep running as long as the process stays alive!