如果在 Android 中连接到 BLE 设备失败,如何通知用户?

Posted

技术标签:

【中文标题】如果在 Android 中连接到 BLE 设备失败,如何通知用户?【英文标题】:How to notify user if connection fails to BLE device in Android? 【发布时间】:2017-04-27 19:48:28 【问题描述】:

如果用户尝试连接的设备未连接,除了等待和测试连接外,我如何通知用户。尝试 connectGatt() 后连接失败似乎没有任何回调。 谢谢!

【问题讨论】:

【参考方案1】:

方法:connGATT()有3个参数。第三个是回调:

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

如果你想知道连接是否成功,你应该添加覆盖方法:

@Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState)

这是链接。https://developer.android.com/guide/topics/connectivity/bluetooth-le.html

整个回调如下所示:

    private final BluetoothGattCallback mGattCallback =
            new BluetoothGattCallback() 
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState) 
            String intentAction;
            if (newState == BluetoothProfile.STATE_CONNECTED) 
                intentAction = ACTION_GATT_CONNECTED;
                mConnectionState = STATE_CONNECTED;
                broadcastUpdate(intentAction);
                Log.i(TAG, "Connected to GATT server.");
                Log.i(TAG, "Attempting to start service discovery:" +
                        mBluetoothGatt.discoverServices());

             else if (newState == BluetoothProfile.STATE_DISCONNECTED) 
                intentAction = ACTION_GATT_DISCONNECTED;
                mConnectionState = STATE_DISCONNECTED;
                Log.i(TAG, "Disconnected from GATT server.");
                broadcastUpdate(intentAction);
            
        

        @Override
        // New services discovered
        public void onServicesDiscovered(BluetoothGatt gatt, int status) 
            if (status == BluetoothGatt.GATT_SUCCESS) 
                broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
             else 
                Log.w(TAG, "onServicesDiscovered received: " + status);
            
        

        @Override
        // Result of a characteristic read operation
        public void onCharacteristicRead(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic,
                int status) 
            if (status == BluetoothGatt.GATT_SUCCESS) 
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            
        
     ...
    ;
...

【讨论】:

嗨,我确实设置了回调,但是“连接失败”没有状态更改。经典蓝牙有“mmSocket.connect()”,如果连接没有发生,它会抛出异常。我不知道如何判断连接是否失败,除非通过轮询设备或“State_Connected”标志超时。有什么我想念的吗?谢谢。 看到你有“status”和“newStatus”吧?如果 "status" !=GATT_SUCCESS 表示 gatt 连接失败,如果 "status" == GATT_SUCCESS && "newState" == STATE_CONNECTED 表示连接成功并获得 Peripheral 连接。 如果我尝试连接但设备不可用,onConnectionStateChange 根本不会触发,所以我无法检查状态。

以上是关于如果在 Android 中连接到 BLE 设备失败,如何通知用户?的主要内容,如果未能解决你的问题,请参考以下文章

设备在Android中连接到WiFi时如何获取蜂窝网络的IP地址

强制关闭连接到 Android 应用程序的 BLE 设备会触发状态为 8 的 onConnectionStateChange

与 BLE 设备保持连接的 Android 应用

为啥在 Android 中将 autoConnect 设置为 true 时,App 不会重新连接到 BLE 设备?

Android 4.4:低功耗蓝牙;无需扫描 BLE 设备即可连接

此平台不支持 CoreBluetooth BLE 硬件