0

他只是我的代码。在某处看到这个例子。但它没有用。

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)”

也许我必须实现一个完整的服务器、服务和广播接收器?谢谢您的帮助!

4

1 回答 1

0

BluetoothGattService简单地使用构造函数构造 a 是行不通的new BluetoothGattService(Battery_Service_UUID, 0);。该代码使用旨在在您的 Android 应用程序中托管GattService,因此您收到的错误是预期的。

为了从 Android 上的外部蓝牙设备读取 GATT 蓝牙特性,您必须首先使用异步 API 执行多个步骤:

  1. 扫描并发现蓝牙设备。(可能有不止一个可见,所以你必须以某种方式选择正确的。)

    mBluetoothAdapter.startLeScan(mLeScanCallback);
    // the above will bring a callback to onLeScan(final BluetoothDevice device, int rssi,
        byte[] scanRecord)
    
  2. 连接到设备

    device.connectGatt(mContext, false, mGattCallback);
    // the above will cause a callback to onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
    
  3. 发现设备的服务

    gatt.discoverServices();
    // the above will bring a callback to onServicesDiscovered(BluetoothGatt gatt, int status) 
    
  4. 从服务中读取特征

    gatt.getCharacteristic(Battery_Level_UUID);
    

最后一步中的代码行是问题中的代码尝试执行的操作并导致 null。为此需要执行前三个步骤。

有关更多信息,请参见此处:https ://developer.android.com/guide/topics/connectivity/bluetooth-le.html

于 2017-11-07T14:44:46.877 回答