按后退按钮退出应用程序时服务不会停止

Service doesn't stop when exiting app by press of the back button

在我的应用程序中,服务在后台启动以处理与 BLE 设备的 BLE 通信。我在搜索 BLE 设备的应用程序启动时有一个 Activity (StartActivity),当它找到它时,它启动服务 (BleService),将找到的设备交给它,然后绑定到它接收来自 BleService 的广播。
BleService 建立 BLE 连接,设置不同特征的通知器并读取它们。由于它获得了最初需要的所有信息,因此发送了一个广播。
此广播导致 StartActivity 切换到另一个 Activity (MainActivity),然后它再次绑定到 BleService 并对 BleService 的广播作出反应。
到目前为止,一切都很好。

当我在 MainActivity 中按后退按钮时,应用 'closes'。现在,当我重新启动该应用程序时(通过单击其图标或在最近的应用程序列表中),该应用程序返回到 StartActivity 并且无法连接到 BLE 设备。由于我的 BLE 设备上的 LED 不断向我发出信号,它已连接,我认为第一个 BleService 仍然 运行 并连接到 BLE 设备。
我通过向 BleService 的 onDestroy() 方法添加日志输出来检查这一点,是的,没有调用 onDestroy()。当我通过最近的应用程序列表关闭我的应用程序时,它被调用。

通过使用后退按钮关闭我的应用程序时我应该怎么做?

编辑: 所以我想从我的问题中提炼出我的问题:
当我在 MainActivity 中按下后退按钮关闭我的应用程序,然后通过最近的应用程序列表或再次通过其图标启动它时,我卡在 StartActivity 中。这是因为 StartActivity 找不到 BLE 设备,因为它仍然连接到 运行 BleService。
我怎样才能避免这种情况?

Android 服务应保持 运行 即使其父应用程序终止。这是一个重要的功能,即使在应用程序 crashes/closes/gets 被杀死时也能够执行任何关键操作...

对您而言,这仅意味着您必须在退出应用程序时关闭您的服务,至少如果这是您打算执行的操作。这样做非常简单:

stopService(new Intent(ActivityName.this, ServiceClassName.class));

如果您通过 Context.startService() 启动 Service,则必须通过 Context.stopService() 或服务本身调用 stopSelf() 停止它。 Binding/unbinding 只有当绑定是 Service 最初启动的方式时(例如,不使用 startService()),服务才会停止它。

我不确定您希望在按下“后退”时发生什么,但您可以查看 this answer 来帮助您确定该服务是否 运行 以及采取适当的行动。

If your client and server code is part of the same .apk and you are binding to the service with a concrete Intent (one that specifies the exact service class), then you can simply have your service set a global variable when it is running that your client can check.

We deliberately don't have an API to check whether a service is running because, nearly without fail, when you want to do something like that you end up with race conditions in your code.