gpt4 book ai didi

Android - 确保在服务进程被操作系统终止时释放唤醒锁

转载 作者:行者123 更新时间:2023-11-29 15:12:42 24 4
gpt4 key购买 nike

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

话虽如此,我知道 Android 操作系统会在需要内存时在后台终止服务/应用程序。因此,我的服务可能会被终止。

发生这种情况时,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? .

关于Android - 确保在服务进程被操作系统终止时释放唤醒锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29005094/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com