Android - 确保在服务进程被 OS 终止时释放唤醒锁

Android - Ensuring that Wakelock is released when a Service's process is killed by OS

我希望我的 FusedLocationProvider 即使在屏幕关闭时也能 ping 定位。为此,在我的服务中,我有一个 PARTIAL_WAKE_LOCK,以保持 CPU 运行ning 并确保即使在屏幕关闭时服务也能继续 运行。

也就是说,我知道 Android OS 需要内存时会在后台关闭 services/apps。因此,我的服务可能会被终止。

发生这种情况时,Service 中的 onDestroy() 不能保证被调用。如果是这样,我如何确保释放 WakeLock?

我在onStartCommand中调用mWakeLock.acquire();,在onDestroy中我调用mWakeLock.release();

how do I ensure that the WakeLock gets released?

根据 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. 

这意味着如果任何这些方法中的代码当前正在执行,那么在代码执行完成之前,进程不会被终止(或者至少会被赋予非常高的优先级)。

但是,对您的问题的简短回答是 没有 方法可以确保 onDestroy()onPause() 被调用。不过,onPause() 被跟注的可能性确实大得多,因此您可以研究一下。还有一种方法,Application.onTerminate(),你可能想用它来进一步研究。该方法仅在 运行 模拟器上的应用程序时调用。

不过,我认为您不必担心内存 泄漏 (假设我们都在同一页面上了解此类泄漏的构成)。当一个进程被杀死时,内存由内核回收,而不是由 GC 回收,因此在这种情况下不会发生内存泄漏。

编辑:

我已经确认,如果进程被杀死,获得的唤醒锁必然会被释放:

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?.