在 Android 上后台运行 BLE

Geo*_*rds 1 android bluetooth nativescript

我目前所在的位置:

我希望能够在 Android 的后台运行我的应用程序中的蓝牙。我已经阅读了各种指南并了解创建意图服务的想法(例如android.app.IntentService并扩展它,onHandleIntent用您想要的行为覆盖它)但是,我不明白这将如何与我现有的行为相互作用?例如,我目前打电话:

...
var bluetoothManager = utils.ad.getApplicationContext().getSystemService(android.content.Context.BLUETOOTH_SERVICE);
adapter = bluetoothManager.getAdapter();
adapter.startLeScan(Bluetooth._scanCallback)
...
Run Code Online (Sandbox Code Playgroud)

(这是在 JavaScript 中,使用 nativescript 运行时,所以不用担心它看起来有点奇怪。)

我想要去的地方:

我希望能够在后台扫描并重新连接配对设备并接收(存储在 SQLite 中)GATT 特征更新。

问题:

那么,如何在如上所述可以在后台运行的服务类型中创建此功能呢?

Emi*_*mil 5

蓝牙 LE Gatt API 基于 Android 的 Binder 机制构建,这意味着它仅在应用程序进程处于活动状态时才工作。您必须确保您的应用程序进程不会被系统终止。最简单的方法是运行前台服务(而不是意向服务)。唯一重要的是前台服务处于活动状态并正在运行,您的服务类本身不需要执行任何操作。但我想最简单的方法是将所有 BLE 代码放入该服务中。请参阅https://developer.android.com/guide/components/services.html#Foreground