2

I want my FusedLocationProvider to ping for location even when the screen is off. For this, in my service, I have a PARTIAL_WAKE_LOCK, to keep the CPU running and to ensure that the service continues to run even when the screen is off.

That being said, I know the Android OS will kill off services/apps in the background when it needs memory. Due to this, my service can be killed off.

When this happens, onDestroy() in the Service is not guaranteed to be called. If that is the case, how do I ensure that the WakeLock gets released?

I call mWakeLock.acquire(); in onStartCommand, and in onDestroy I call mWakeLock.release();

Yash Sampat
  • 30,051
  • 12
  • 94
  • 120
David
  • 7,028
  • 10
  • 48
  • 95

1 Answers1

5

how do I ensure that the WakeLock gets released?

According to the docs:

If the service is currently executing code in its onCreate(), 
onStartCommand(), or onDestroy() methods, then the hosting process will be a 
foreground process to ensure this code can execute without being killed. 

What this means is that if the code in any of those methods is currently being executed, then the process won't be killed (or at least will be given a very high priority) till the code finishes executing.

However, the short answer to your question is that there is NO way to ensure that onDestroy() or onPause() gets called. onPause(), though, does have a far greater probability of getting called, so you could look into that. There is also a method, Application.onTerminate() which you may want to use for further research on this. The method is only called when running the app on emulators.

I don't think you need to worry about a memory leak, though (assuming that we are both on the same page regarding what such a leak constitutes). When a process is killed, the memory is reclaimed by the kernel, not by the GC, so there isn't going to be a memory leak in that case.

EDIT:

I have confirmed that if a process is killed, an acquired wakelock will necessarily be released:

1. Does the android os release a wakelock if the app or service holding it is killed ?.

2. What happens with the partial wake lock if the process that acquires is killed ?.

3. Binders & Death Recipients.

4. How to deal with (orphaned) WakeLocks?.

Community
  • 1
  • 1
Yash Sampat
  • 30,051
  • 12
  • 94
  • 120
  • Yeah, I guess memory leak was poor wording. My main worry is that my WakeLock never gets released and my app will be draining battery due to a CPU always being active. – David Mar 12 '15 at 10:28