蓝牙不可接收消息
蓝牙不可接收消息,个人开发过程中的一些经验,其中有两个需要注意:
因为其他初始化操作,发送都已经调通,但是未收到返回数据。考虑,1.收的时候出现问题。2.发送的时候,数据有问题,
针对于(1):
在接受的时候进行处理:
初始化完BluetoothGattCharacteristic read = service.getCharacteristic(UUID.fromString(“6e400003-b5a3-f393-e0a9-e50e24dcca9e”));
之后对read进行writeDescriptor,
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
boolean enabled) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, “BluetoothAdapter not initialized”);
return;
}
// mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
boolean isEnableNotification = mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
if (isEnableNotification) {
List descriptorList = characteristic.getDescriptors();
if (descriptorList != null && descriptorList.size() > 0) {
for (BluetoothGattDescriptor descriptor : descriptorList) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
}
}
}
针对于(2):
我之前发送的数据时[58x11,12x00,00xaa],发现收到的数据是不完整的,1024个字节每次收214个应该收5次,但是每次只收到3次,修改为:
write.setValue(hexStringToBytes(“23”));
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.trim();
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
public static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
希望有所帮助