onCharacteristicChanged 不断接收 BLE 字节前台服务

问题描述

我在我的活动中写了 BluetoothGattCallback。我还有一个 foreground service 正在运行以捕获用户位置。 当我终止我的应用程序时,我可以看到来自 Bluetooth Low Energy 的广告数据包在 onCharacteristicChanged 中不断接收。

但是当我删除 foreground service 时,一旦我终止应用程序,来自 Bluetooth Low Energy 的广告数据包就会在 onCharacteristicChanged(这是所需状态)中停止接收。

当我杀死应用程序时,如何阻止来自 Bluetooth Low Energy 中的 onCharacteristicChanged 的广告数据包?

解决方法

我认为您对“杀死应用程序”的定义实际上是“破坏正在运行的活动”,这与“杀死应用程序进程”不同。

蓝牙 API 与活动逻辑完全分离。除非您主动采取措施阻止通知到达您的应用进程,并且除非蓝牙连接设备断开,否则它们将继续出现,直到应用进程被终止。

如果您希望在销毁您的 Activity 时停止蓝牙连接,您需要在您的 Activity 中的 #include <stdio.h> #include <string.h> #define A 10 #define B 10 typedef char *string; struct { string product; int age } sales[A][B]; int main(void) { string product = "A"; int age = 20; sales[0][1].product = product; sales[0][1].age = age; printf("Sales: %s\n",sales[0][1].product); } 方法(或您的 Activity 的服务的 onDestroy 方法中)绑定到),例如确保在您的 onDestroy 对象上调用 close 方法。

最后一件事,您在 BluetoothGatt 中得到的是通知或指示。不是广告包。执行扫描时会得到广告数据包。