android 4.3蓝牙ble不叫onCharacteristicRead()
我已经将通知设置为android,它没有调用方法onCharacteristicRead()
???? 它不会进入该function。 为什么会这样?
任何帮助表示赞赏
请求解决方案。
这是我的代码:
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { Log.i(TAG, "Connected to GATT server."); // Attempts to discover services after successful connection. Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices()); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { Log.i(TAG, "Disconnected from GATT server."); } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { gattServices = mBluetoothGatt .getService(SampleGattAttributes.SERVICES_UUID); if (gattServices != null) { gattCharacteristics = gattServices .getCharacteristic(SampleGattAttributes.CHARACTERISTIC_UUID); System.out.println("character-->" + gattCharacteristics); } if (gattCharacteristics != null) { System.out.println("Characteristic not null"); System.out.println("Characteristic Properties-->" + gattCharacteristics.getProperties()); mBluetoothGatt.setCharacteristicNotification(gattCharacteristics, true); } } else { Log.w(TAG, "onServicesDiscovered received: " + status); } } @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { System.out.println("in read"); if (status == BluetoothGatt.GATT_SUCCESS) { byte[] data = characteristic.getValue(); System.out.println("reading"); System.out.println(new String(data)); } } @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { // System.out.println("change"); byte[] data = characteristic.getValue(); System.out.println(new String(data)); } };
先谢谢你!!
首先,如果您通过以下方式阅读了特征,那么onCharacteristicRead
将会触发:
mBluetoothGatt.readCharacteristic(characteristic);
阅读特征和设置通知是两回事。 您希望从中获取数据的特征类型是什么?
是吗:
- 读
- 通知
- 表明
如果它被read
你可以使用mBluetoothGatt.readCharacteristic(characteristic);
读取mBluetoothGatt.readCharacteristic(characteristic);
方法,但如果它首先notify
或indicate
你将必须通过调用以下方式读取特征的descriptor
:
mBluetoothGatt.readDescriptor(ccc);
一旦你读它,它应该通过调用onDescriptorRead
回调来返回数据。
在这里,您可以通过调用通过通知或指示设置(订阅)字符:
mBluetoothGatt.setCharacteristicNotification(characteristic, true)
一旦它返回true
你将需要再次写入描述符(通知或指示的值)
BluetoothGattDescriptor clientConfig = characteristic.getDescriptor(CCC); clientConfig.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); // or //clientConfig.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE); mBluetoothGatt.writeDescriptor(clientConfig);
完成此操作后,每次特征更改时,您都会收到有关特征onCharacteristicChanged
回调的通知。
您可以在此处阅读有关Android上蓝牙连接的更多信息
以及有关蓝牙特性的信息