如何返回BLE外设的连接状态

时间:2017-06-23 22:17:10

标签: bluetooth bluetooth-lowenergy nrf51

我注意到,当外围设备非手动断开时,例如外围设备断电时,方法onConnectionStateChange()并非总是被调用(或者根本没有按时调用)。有没有办法手动获取连接的BLE外设的连接状态而不是等待onConnectionStateChange()触发?我尝试使用BluetoothManager#getConnectionState但这个方法似乎正在访问由调用onConnectionStateChange()的任何线程更新的连接状态,并且实际上并不询问设备是否已连接。换句话说,如果尚未调用BluetoothManager#getConnectionState,则onConnectionStateChange()仅返回false。

这是我的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;
}

1 个答案:

答案 0 :(得分:2)

只要蓝牙控制器向主机蓝牙堆栈报告链接已终止,就会调用onConnectionStateChange。如果在没有正常断开连接的情况下突然断开外围设备的电源,连接将一直保持到监控超时触发为止。在最新的Android版本中,默认值从20秒变为5秒,因为人们抱怨它太长了。 iOS上的默认值为0.72秒。在Android上,您可以通过从外围设备执行连接参数更新请求来手动降低它。

相关问题