我在MainActivity一個按鈕,用於寫入一byte[]
到BLE設備:該程序是否正確寫入藍牙低能量特性?
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Write Char"
android:id="@+id/button2"
android:onClick="onClickWrite" />
和函數onClickWrite
是
public void onClickWrite(View v){
if(mBluetoothLeService != null) {
byte [] data= new byte[3];
data[0] = (byte)(0 & 0xFF);
data[1] = (byte)(255 & 0xFF);
data[2] = (byte)(0 & 0xFF);
mBluetoothLeService.sendData(data);
}
}
其中sendData
是[BluetoothLeService][1]
類的改性功能。當我按下按鈕時,它運行良好。不過,讓我們仔細看看sendData
函數。當我按下按鈕時,它再次搜索服務和特性。在BLE中寫入特性是否正確?
public void sendData(byte[] data){
String lService = "00001c00-d102-11e1-9b23-00025b00a5A5";
String lCharacteristic = "00001c03-d102-11e1-9b23-00025b00a5a5";
BluetoothGattService mBluetoothLeService = null;
BluetoothGattCharacteristic mBluetoothGattCharacteristic = null;
for (BluetoothGattService service : mBluetoothGatt.getServices()) {
if ((service == null) || (service.getUuid() == null)) {
Log.d("TAG","Something is null");
continue;
}
if (lService.equalsIgnoreCase(service.getUuid().toString())) {
Log.d("TAG","service.getUuid().toString()="+service.getUuid().toString());
mBluetoothLeService = service;
}
}
if(mBluetoothLeService!=null) {
mBluetoothGattCharacteristic =
mBluetoothLeService.getCharacteristic(UUID.fromString(lRgbCharacteristic));
}
else{
Log.d("TAG","mBluetoothLeService is null");
}
if(mBluetoothGattCharacteristic!=null) {
mBluetoothGattCharacteristic.setValue(data);
boolean write = mBluetoothGatt.writeCharacteristic(mBluetoothGattCharacteristic);
Log.d("TAG","writeCharacteristic:"+write);
}
else{
Log.d("TAG", "mBluetoothGattCharacteristic is null");
}
}
不錯;但你也可以考慮一個處理程序來解析數據 –