我有两个要连接的设备。当我离开应用程序时,我将与设备断开连接。两者都经历相同的过程,但有时其中一个设备会保持连接,直到我强制关闭应用程序。
我在设备上有指示灯,确认它仍然认为它已连接,并且应用程序的其他实例无法连接到它,直到我强制关闭第一个。在下面的日志中,第一个列出的设备保持连接。
//call gatt.disconnect();
BluetoothGatt: cancelOpen() - device: F0:3D:A0:04:CA:E7
BluetoothGatt: onClientConnectionState() - status=0 clientIf=7 device=F0:3D:A0:04:CA:E7
//wait for connection state change callback then call gatt.close();
BluetoothGatt: close()
BluetoothGatt: unregisterApp() - mClientIf=7
//call gatt.disconnect();
BluetoothGatt: cancelOpen() - device: FF:A9:CA:EF:08:A4
BluetoothGatt: onClientConnectionState() - status=0 clientIf=5 device=FF:A9:CA:EF:08:A4
//wait for connection state change callback then call gatt.close();
BluetoothGatt: close()
BluetoothGatt: unregisterApp() - mClientIf=5
在我调用 gatt.close() 之后,我抓住了 BluetoothManager 并在已连接设备列表中查找我的设备。它在列表中。
从BluetoothGattCallback
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
final String address = gatt.getDevice().getAddress();
if (newState == BluetoothProfile.STATE_CONNECTED) {
onConnected(gatt, address);
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
onDisconnected(gatt, address);
}
}
private void onDisconnected(BluetoothGatt gatt, String address) {
Log.v(TAG, address + " disconnected");
if (devices.containsKey(address)) {
devices.get(address).setState(Connection.STATE_DISCONNECTED);
connect(gatt.getDevice());
} else {
gatt.close();
verifyDisconnect(gatt, address);
}
}
private void verifyDisconnect(BluetoothGatt gatt, String address) {
BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
final List<BluetoothDevice> devices = bluetoothManager.getConnectedDevices(BluetoothProfile.GATT);
for (final BluetoothDevice device : devices) {
if (device.getAddress().equals(address)) {
Log.d(TAG, address + " is still connected!!!!");
addCommand(new DisconnectCommand(gatt));
break;
}
}
}
此类被添加到命令队列中。
public class DisconnectCommand extends BluetoothCommand {
private final BluetoothGatt gatt;
public DisconnectCommand(BluetoothGatt gatt) {
this.gatt = gatt;
priority = BluetoothCommand.DISCONNECT_PRIORITY;
}
public boolean execute() {
gatt.disconnect();
return true;
}
}