他只是我的代码。在某处看到这个例子。但它没有用。
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)'在空对象引用上
也许我必须实现完整的服务器,服务和广播接收器? 谢谢你的帮助!
答案 0 :(得分:0)
使用构造函数BluetoothGattService
简单地构造new BluetoothGattService(Battery_Service_UUID, 0);
是行不通的。该代码用法旨在用于托管您的Android应用中的GattService,因此您可能会遇到错误。
为了从Android上的外部蓝牙设备读取GATT蓝牙特性,您必须先使用异步API完成许多步骤:
扫描并发现蓝牙设备。 (可能有多个可见,所以你必须选择正确的。)
mBluetoothAdapter.startLeScan(mLeScanCallback);
// the above will bring a callback to onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord)
连接到设备
device.connectGatt(mContext, false, mGattCallback);
// the above will cause a callback to onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
发现设备的服务
gatt.discoverServices();
// the above will bring a callback to onServicesDiscovered(BluetoothGatt gatt, int status)
从服务中读取特征
gatt.getCharacteristic(Battery_Level_UUID);
最后一步中的代码行是问题中的代码尝试执行的操作并导致null。为此,需要执行前三个步骤。
有关详细信息,请参阅此处:https://developer.android.com/guide/topics/connectivity/bluetooth-le.html