问题描述
我无法从 Android 上的特性读取数据,但能够在 iOS 设备上读取数据。谁能告诉我我遗漏了什么,以便数据也可以在 Android 上读取。
连接设备:-
try {
await device.connect();
} catch (error) {
if (error.code != 'already_connected') {
throw error;
}
} finally {
List<BluetoothService> deviceServices = await device.discoverServices();
_examineDeviceServicesForTestConnection(deviceServices,device);
}
检查具有特征读取和通知的服务:-
_examineDeviceServicesForTestConnection(
List<BluetoothService> services,BluetoothDevice device) async {
BluetoothCharacteristic testReadCharacteristic;
BluetoothCharacteristic testWriteCharacteristic;
serviceLoop:
for (BluetoothService service in services) {
if (service.characteristics.isNotEmpty) {
characteristicLoop:
for (BluetoothCharacteristic characteristic
in service.characteristics) {
if (characteristic.properties.notify) {
testReadCharacteristic = characteristic;
}
if (characteristic.properties.write) {
testWriteCharacteristic = characteristic;
}
}
if (testReadCharacteristic != null && testWriteCharacteristic != null) {
final testCommand = "TEST_COMMAND";
final convertedTestCommand = utf8.encode(testCommand);
//reading data from characteristics
_readDataFromcharacteristics(
testReadCharacteristic,testWriteCharacteristic,device);
//write command to device
await testWriteCharacteristic.write(convertedTestCommand);
}
}
}
}
从特征中读取数据:-
_readDataFromcharacteristics(BluetoothCharacteristic readerCharx,BluetoothCharacteristic writerCharx,BluetoothDevice device) async {
await readerCharx.setNotifyValue(true);
readerCharx.value.listen((response) {
var decodedResponse = utf8.decode(response);
print(decodedResponse);
});
}
蓝牙和位置的必要权限
<uses-permission android:name="android.permission.BLUetoOTH" />
<uses-permission android:name="android.permission.BLUetoOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)