我注意到,onConnectionStateChange()
当外围设备被非手动断开连接时,例如当外围设备断电时,该方法并非总是被调用(或只是没有按时调用)。有没有办法手动获取连接的 BLE 外围设备的连接状态,而不是等待onConnectionStateChange()
触发?我尝试使用BluetoothManager#getConnectionState
,但这种方法似乎正在访问由正在调用的任何线程更新的连接状态onConnectionStateChange()
,并且实际上并没有询问设备是否已连接。换句话说,如果尚未调用,BluetoothManager#getConnectionState
则返回 false 。onConnectionStateChange()
这是我的isConnected
方法
public boolean isConnected(){
// If the device has never connected, it's gatt service is null.
if(mGatt != null){
BluetoothManager btm =
(BluetoothManager)
MainActivity.mMainActivity.getSystemService(Context.BLUETOOTH_SERVICE);
int state = btm.getConnectionState(mGatt.getDevice(), BluetoothProfile.GATT);
return state == 2;
}
// The gat service is null, the device is not connected, return false.
return false;
}