【发布时间】:2021-09-02 13:12:32
【问题描述】:
我正在使用 android BLE。在这个任务中,android 应用程序应该连接到多个 BLE 设备,这没关系。我可以连接成功。
我知道这个代码需要连接BLE设备:
BluetoothGatt gaat = device.connectGatt(getApplicationContext(), false, gattCallback);
我使用Map<String, BluetoothGatt> connectedDeviceMap 来保留BLE 设备addresses 和BluetoothGatt:
List<BluetoothDevice> devices = bluetoothManager.getConnectedDevices(BluetoothProfile.GATT);
if (devices != null && !(devices.isEmpty())) {
for (BluetoothDevice device : devices) {
if (device.getType() == BluetoothDevice.DEVICE_TYPE_LE) {
BluetoothDevice d = bluetoothAdapter.getRemoteDevice(device.getAddress());
gatt = d.connectGatt(getApplicationContext(), false, gattCallback);
connectedDeviceMap.put(d.getAddress(), gatt);
}
}
}
如您所见,为了获取每个设备的 gatt 值,我需要调用 connectGatt 函数。但是当此函数多次调用时,设备与应用程序断开连接(我认为这是因为 BLE 的内存已满)
所以我使用close() 释放所有内存并再次连接:
List<BluetoothDevice> devices = bluetoothManager.getConnectedDevices(BluetoothProfile.GATT);
if (devices != null && !(devices.isEmpty())) {
for (BluetoothDevice device : devices) {
if (device.getType() == BluetoothDevice.DEVICE_TYPE_LE) {
BluetoothDevice d = bluetoothAdapter.getRemoteDevice(device.getAddress());
gatt = d.connectGatt(getApplicationContext(), false, gattCallback);
connectedDeviceMap.put(d.getAddress(), gatt);
gatt .close();
}
}
}
但这不起作用,并且设备在多次调用connectGatt时与应用程序断开连接。
【问题讨论】:
标签: java android android-studio bluetooth bluetooth-lowenergy