BLE onServicesDiscovered()没有返回特征数组

时间:2017-11-20 05:30:35

标签: android bluetooth bluetooth-lowenergy

我已在我的应用中实施了BLE中心。 步骤:

  1. 获取BluetoothManager

    mBluetoothManager =(BluetoothManager)mContext.getSystemService(Context.BLUETOOTH_SERVICE);

    mBluetoothAdapter = mBluetoothManager.getAdapter();

  2. 扫描设备

  3. 连接设备

    mGatt = bluetoothDevice.connectGatt(this,false,gattCallback);

  4. 处理回调并启动服务发现

  5. 设备连接后,我正在拨打电话来发现服务。

    gatt.discoverServices();
    

    一旦发现服务,我就会在

    中捕获它
    private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            Log.i("onConnectionStateChange", "Status: " + status);
            switch (newState) {
                case BluetoothProfile.STATE_CONNECTED:
                    Log.i("gattCallback", "STATE_CONNECTED");
                    gatt.discoverServices();
                    break;
    
                case BluetoothProfile.STATE_DISCONNECTED:
                    mGatt = null;
                    mBluetoothSingleTonClass.saveGatt(mGatt);
                    deviceDisconnected();
                    Log.e("gattCallback", "STATE_DISCONNECTED");
                    break;
    
                case BluetoothProfile.STATE_CONNECTING :
                    Log.e("gattCallback", "STATE_CONNECTING");
                    break;
    
                default:
                    Log.e("gattCallback", "STATE_OTHER");
            }
        }
    
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    
            List<BluetoothGattService> services = new ArrayList<>();
            services.addAll(gatt.getServices());
    
            Log.d("onServicesDiscovered", "uuid::" + gatt.getServices().get(0).getUuid());
            Log.d("onServicesDiscovered", "uuid::" + gatt.getServices().get(1).getUuid());
            Log.d("onServicesDiscovered", "uuid::" + gatt.getServices().get(2).getUuid());
    
            Log.d("onServicesDiscovered", "chars::" + gatt.getServices().get(2).getCharacteristics().size());
            Log.d("onServicesDiscovered", "chars::" + gatt.getServices().get(0).getCharacteristics().size());
            Log.d("onServicesDiscovered", "chars::" + gatt.getServices().get(1).getCharacteristics().size());
    
    
        }
    };
    

    问题是 gatt 为我提供了设备所具有的所有服务,但它在少数移动设备中提供了空特征数组。 示例:gatt.getServices().get(0).getCharacteristics().size() 这在Nexus中运行良好,但几天后它给我空数组,即大小为零。 我做错了吗?这是移动设备的问题吗?任何参考链接都会有所帮助。

1 个答案:

答案 0 :(得分:0)

如果设备在发现过程中断开连接,则可能会给出一个空(或太短)列表。您应检查回调中的状态代码,并假设服务在0(成功)时有效。