Jef*_*sen 5 android bluetooth bluetooth-lowenergy android-ble
我有两个正在连接的设备。当我离开应用程序时,我会断开与设备的连接。两者都经历相同的过程,但有时其中一个设备会保持连接,直到我强制关闭应用程序。
我的设备上有指示灯,确认它仍然认为它已连接,并且应用程序的其他实例无法连接到它,直到我强行关闭第一个实例。在下面的日志中,第一个列出的设备保持连接。
//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
Run Code Online (Sandbox Code Playgroud)
调用 gatt.close() 后,我获取蓝牙管理器并在已连接设备列表中查找我的设备。它在列表中。
从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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
此类被添加到命令队列中。
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;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 0
尝试:
public void disconnect() {
if (blegatt== null) {
Log.w(TAG, "BluetoothAdapter not initialized");
}
else {
bleGatt.disconnect();
close();
gatt = null;
}
}
/**
* After using a given BLE device, the app must call this method to ensure resources are
* released properly.
*/
public void close() {
if (gatt == null) {
return;
}
gatt.close();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5499 次 |
| 最近记录: |