Android BLE连接多个设备后自动断开连接可能是由于使用了相同的连接名称或使用了相同的连接选项的问题。在解决此问题之前,请确保您的应用程序已打开蓝牙和被授权使用蓝牙。
以下是可能解决此问题的示例代码,其中使用了唯一的连接名称和连接选项:
private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private HashMap mBluetoothDevices = new HashMap<>();
private HashMap mBluetoothGatts = new HashMap<>();
public void connectDevice(BluetoothDevice device) {
String deviceAddress = device.getAddress();
if (mBluetoothGatts.containsKey(deviceAddress)) {
// Already connected
return;
}
BluetoothGatt bluetoothGatt = device.connectGatt(this, false, mGattCallback);
mBluetoothGatts.put(deviceAddress, bluetoothGatt);
mBluetoothDevices.put(deviceAddress, device);
}
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
// Implement essential callbacks
};
此代码段包括以下步骤:
通过使用唯一的连接名称和连接选项,可确保当多个设备连接到Android BLE时不会自动断开连接。
上一篇:AndroidBLE广告