ans*_*992 7 android bluetooth-lowenergy beacon
我正在尝试将文本数据写入我的BLE设备.所以,我正在关注Android蓝牙GATT课程来完成这项任务.但我发现将文本写入特征是好的,但在尝试检索特征值时,它返回null.
MyCode:
public void writeCharacteristic(BluetoothGattCharacteristic characteristic,
String text) {
String TAGS ="MyBeacon";
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAGS, "BluetoothAdapter not initialized");
return;
} else {
Log.w(TAGS, "Writting ... ");
}
byte[] data = hexStringToByteArray(text);
Log.w(TAGS, "Writting text = " + data);
try {
characteristic.setValue(URLEncoder.encode(text, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
boolean writeValue = mBluetoothGatt.writeCharacteristic(characteristic);
Log.w(TAGS, "Writting Status = " + writeValue);
}
Run Code Online (Sandbox Code Playgroud)
//成功onCharacteristicWrite也被调用//
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
String TAGS ="MyBeacon";
String text = null;
try {
text = new String(characteristic.getValue(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.w(TAGS, "onCharacteristicWrite = " + text+" :: "+status);
}
Run Code Online (Sandbox Code Playgroud)
但在尝试读取特征时,它返回null.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
final byte[] data = gattCharacteristic.getValue(); // returns null
if (data != null && data.length > 0) {
Log.d("MyBeacon", " Read Data ")
} else {
Log.d("MyBeacon", " Data is null")
}
}
Run Code Online (Sandbox Code Playgroud)
请帮帮我,建议我成功写入和读取数据到我的Beacon的解决方案.
小智 6
语法应如下所示,
mBluetoothGatt.readCharacteristic(characteristic);
Run Code Online (Sandbox Code Playgroud)
读取特征:
您可以使用以下方式读取特征 mBluetoothGatt.readCharacteristic(characteristic);
您可能必须按如下方式读取特征的描述符,
mBluetoothGatt.readDescriptor(ccc);
Run Code Online (Sandbox Code Playgroud)
读取后,它应该通过调用 onDescriptorRead 回调返回数据。在这里,您可以通过通知或调用指示来设置(订阅)特征:
mBluetoothGatt.setCharacteristicNotification(characteristic, true)
Run Code Online (Sandbox Code Playgroud)
一旦返回 true,您将需要再次写入描述符(通知或指示的值)
BluetoothGattDescriptor clientConfig = characteristic.getDescriptor(CCC);
clientConfig.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
//clientConfig.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
mBluetoothGatt.writeDescriptor(clientConfig);
Run Code Online (Sandbox Code Playgroud)
完成此操作后,每次特征发生变化时,您都会通过 onCharacteristicChanged 回调收到通知。
如果您在实施时遇到任何问题,请更新我,
| 归档时间: |
|
| 查看次数: |
7619 次 |
| 最近记录: |