他只是我的代码。在某处看到这个例子。但它没有用。
private static final UUID Battery_Service_UUID = UUID.fromString("0000180F-0000-1000-8000-00805f9b34fb");
private static final UUID Battery_Level_UUID = UUID.fromString("00002a19-0000-1000-8000-00805f9b34fb");
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private BluetoothGattService mBluetoothGatt;
...
public void readCustomCharacteristic() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w("Beacons", "BluetoothAdapter not initialized");
return;
}
/*check if the service is available on the device*/
BluetoothGattService mBatteryService = mBluetoothGatt;
if(mBatteryService == null){
Log.w("Beacons", "Battery BLE Service not found");
return;
}
/*get the read characteristic from the service*/
BluetoothGattCharacteristic mReadCharacteristic = mBatteryService.getCharacteristic(Battery_Level_UUID);
if(mReadCharacteristic.getStringValue(0) == null){
Log.w("Beacons", "Failed to read characteristic");
} else {
Log.i("Beacons", "Battery Level: " + mReadCharacteristic.getValue());
}
}
具体来说,我得到一个 NullPointerException:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.String android.bluetooth.BluetoothGattCharacteristic.getStringValue(int)”
也许我必须实现一个完整的服务器、服务和广播接收器?谢谢您的帮助!