当我禁用蓝牙参数时,我遇到了一个问题。
我使用广播接收器侦听此操作,并且当其状态关闭时,我调用一种方法断开与外围设备的连接。
在我的日志中,我仅看到D/BluetoothGatt: cancelOpen()
,但是根据BluetoothGatt.class
,该服务以BluetoothGattCallback
的{{1}}方法调用我们的disconnect
变成了onConnectionStateChanged
, 20或30秒(主管超时)后也什么也没有。
当我想使用内部方法直接断开设备连接时,
这是断开连接的方法:
DEVICE_DISCONNECTED
我用反射检查了mClientIf是否等于0或mService是否为Null,但他转到下一步并输入try / catch。所以我不明白Android的行为
答案 0 :(得分:0)
我根据该库和此类找到了一个解决方案: https://github.com/NordicSemiconductor/Android-BLE-Library/blob/master/ble/src/main/java/no/nordicsemi/android/ble/BleManager.java
private final BroadcastReceiver mBluetoothStateBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
final int previousState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, BluetoothAdapter.STATE_OFF);
switch (state) {
case BluetoothAdapter.STATE_TURNING_OFF:
case BluetoothAdapter.STATE_OFF:
if (mConnected && previousState != BluetoothAdapter.STATE_TURNING_OFF && previousState != BluetoothAdapter.STATE_OFF) {
// The connection is killed by the system, no need to gently disconnect
mGattCallback.notifyDeviceDisconnected(mBluetoothDevice);
}
// Calling close() will prevent the STATE_OFF event from being logged (this receiver will be unregistered). But it doesn't matter.
close();
break;
}
}
};
我根据需要对其进行了调整,但是我还使用断开的设备信息来调度事件,并调用自己的close方法来释放资源并为另一个连接做准备。