我需要在 Android 设备上通过蓝牙接收 5 字节帧。我发送数据帧没有问题,但我不知道如何正确接收它。我不需要接收字符串,只需要接收字节值。 有人有类似的代码吗? 我正在 Android Studio 2.2.3 中编程
最佳答案
您必须启用尊重特征的通知/指示。 写完命令后。您将从 GATT 以字节形式获得回调。
1) 扫描设备
2)与设备连接
device.connectGatt(mContext, autoConnect,BluetoothGattCallback, BluetoothDevice.TRANSPORT_LE);
BluetoothGattCallback - 回调
在此回调中,您有多个继承的方法。为了您的目的,请使用此
继承此方法,从外设获取字节。
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
throw new RuntimeException("Stub!");
}
3) 您必须根据您的外设要求启用指示/通知。
//用于启用指示 - 并将您的参数作为您的特征。
private static final UUID CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
public final boolean enableIndications(final BluetoothGattCharacteristic characteristic) {
Log.d("CheckData", "enableIndications");
final BluetoothGatt gatt = mBluetoothGatt;
if (gatt == null || characteristic == null)
return false;
// Check characteristic property
final int properties = characteristic.getProperties();
if ((properties & BluetoothGattCharacteristic.PROPERTY_INDICATE) == 0)
return false;
gatt.setCharacteristicNotification(characteristic, true);
final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
return gatt.writeDescriptor(descriptor);
}
return false;
}
//用于启用通知 - 并将您的参数作为您的特征。
protected final boolean enableNotifications(final BluetoothGattCharacteristic characteristic, boolean enable) {
final BluetoothGatt gatt = mBluetoothGatt;
if (gatt == null || characteristic == null)
return false;
// Check characteristic property
final int properties = characteristic.getProperties();
if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) == 0)
return false;
gatt.setCharacteristicNotification(characteristic, enable);
final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
return gatt.writeDescriptor(descriptor);
}
return false;
}
4) 为您尊敬的特质写下值(value)观。
5) 将响应您注册的回调BluetoothGattCallback
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
characteristic.getStringValue(1) // Output Bytes
characteristic.getValue() // Output as Byte Array
Log.d("Values", characteristic.getStringValue(1));
}
characteristic.getStringValue(1)//从特定偏移量以字符串形式输出字节 characteristic.getValue()//输出为字节数组
希望这个回答对您有帮助。
欢呼投票
快乐编码
关于java - 如何在Android设备上使用Android应用程序通过蓝牙接收5字节数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41740621/