为什么在 IntentService 中进行的 BLE 扫描即使在服务被销毁时仍能继续工作?

Why a BLE scanning made in an IntentService keeps on working even when the service is destroyed?

我在 Android 开发的第一个应用程序涉及后台 BLE 扫描。该应用程序有两个按钮来启动服务(进行扫描并记录结果)和停止服务。

documentation我了解了Service和IntentService的区别。我怀疑使用 IntentService 不是最好的方法,因为 Android 系统在处理传递给它的所有意图时破坏服务,因此在服务创建的工作线程中扫描 运行也会停止工作。但是,我想尝试一下以测试我的知识。

正如我所料,该服务在创建后几乎立即被销毁。但是,通知检测到的新设备的日志不断出现,这意味着即使服务被破坏,扫描过程也会继续工作。当我关闭 main activity 时,扫描终于停止了。我想知道为什么扫描进程似乎绑定到主 activity 的线程而不是意图服务创建的线程(自动)。为什么即使服务已被销毁,扫描进程仍继续运行?

我找到了一些与服务和 BLE 扫描相关的 SO 答案 ( and here),但没有人解决这个特定主题。你能帮我点忙吗?

根据 Process Priorities blog post:

Android doesn’t go killing things just for the sake of killing things (remember: starting things from scratch isn’t free!), so these processes can potentially stay around for some time before being reclaimed due to memory needs from anything in a higher category, killed in order of least recent usage (oldest is reclaimed first).

因此,即使您的服务已停止,您的进程仍可在内存中保留一段时间。由于您没有在 onDestroy 上特别停止 BLE 扫描,该工作将继续进行,直到您的进程被终止以回收内存。