在android的蓝牙4.0的开发中,我们经常会用到服务,特征,
正常情况下,我们会在某个服务中通过uuid取出需要的特征,然后对特征进行读写操作,
下面上一份个人用的读写和设置通知的方法,,,也许这样不太友好,但是个人使用习惯不同..仅供参考
/** * 发送指令 * * @param hex 发送的16进制内容 * @param uuid 需要操作的特征uuid * @param type 操作类型(1=读,2=写,3=信号强度,4=通知) * @param uuidService 服务的uuid * * @return */ private boolean sendCmd(byte[] hex, UUID uuid, int type, UUID uuidService) { boolean sendOk = false; try { BluetoothGatt gatt = mBluetoothGatt; if (gatt != null) { BluetoothGattService mGattService = MyBleDeviceUtils.getService(gatt, uuidService); if (mGattService != null) { BluetoothGattCharacteristic mCharacteristic = MyBleDeviceUtils.getServiceWrite (mGattService, uuid); if (mCharacteristic != null) { if (hex != null) { //写入的内容 mCharacteristic.setValue(hex); } mCharacteristic.setWriteType(BluetoothGattCharacteristic .WRITE_TYPE_NO_RESPONSE);//设置类型 switch (type) { case 1: sendOk = gatt.readCharacteristic(mCharacteristic); break; case 2: sendOk = gatt.writeCharacteristic(mCharacteristic); break; case 3: sendOk = gatt.readRemoteRssi(); break; case 4: sendOk = gatt.setCharacteristicNotification(mCharacteristic, true); List<BluetoothGattDescriptor> mm = mCharacteristic.getDescriptors(); if (sendOk) { for (BluetoothGattDescriptor bluetoothGattDescriptor : mm) { bluetoothGattDescriptor.setValue(BluetoothGattDescriptor .ENABLE_NOTIFICATION_VALUE); gatt.writeDescriptor(bluetoothGattDescriptor); } } break; } } } } } catch (Exception e) { MyLog.e(TAG, "读/写/设置通知,异常:" + e.toString()); e.printStackTrace(); } return sendOk; }
在上面的代码中设置通知有个坑,直接设置
sendOk = gatt.setCharacteristicNotification(mCharacteristic, true);
会不生效,没有通知返回,必须把特征下面的BluetoothGattDescriptor全部写入
BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
内容才会有效..