连接服务蓝牙低功耗Android后读取特性值

时间:2017-12-06 16:47:32

标签: android bluetooth bluetooth-lowenergy

建立连接后,我想从特性中读取值并将值保存在字节数组中。

这是我在BluetoothLeService内部阅读的功能:

  public byte[] readWhiteAndIntensityCharacteristic() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
    Log.w(TAG, "BluetoothAdapter not initialized");
    return null;
}
/*check if the service is available on the device*/
BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString(UuidAdresssService));
if (mCustomService == null) {
    Log.w(TAG, "Custom BLE Service not found");
    return null;
}
/*get the read characteristic from the service*/
BluetoothGattCharacteristic mReadCharacteristic = mCustomService.getCharacteristic(UUID.fromString(UuidAdresssWhiteAndIntensityCharastic));
byte[] messageByte = mReadCharacteristic.getValue();
if (messageByte != null && messageByte.length > 0) {
    final StringBuilder stringBuilder = new StringBuilder(messageByte.length);
    for (byte byteChar : messageByte)
        stringBuilder.append(String.format("%02X", byteChar));
    s = "0x" + stringBuilder.toString();
    Log.v("Scan Activity", s);
    if (mBluetoothGatt.readCharacteristic(mReadCharacteristic) == false) {
        Log.w(TAG, "Failed to read characteristic");
    }
}
return messageByte;

} 在我的DeviceControlActivity中调用此函数:

    public void getStartUpValue(){
    Log.w(TAG, "Reading completed");}
  if(mBluetoothLeService.readWhiteAndIntensityCharacteristic() == null)
  {
      Log.w(TAG, "FAILED Reading value failed");
  }
    startValue = mBluetoothLeService.readWhiteAndIntensityCharacteristic();
    Log.w(TAG, "Reading completed");

}

在建立连接后调用getStartUpValue函数。

  private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
    final String action = intent.getAction();
    if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
        mConnected = true;
        updateConnectionState(R.string.connected);
        invalidateOptionsMenu();
    } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
        mConnected = false;
        updateConnectionState(R.string.disconnected);
        invalidateOptionsMenu();
        clearUI();
    } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
        // Show all the supported services and characteristics on the user interface.
        mBluetoothLeService.getSupportedGattServices();
        getStartUpValue();

    } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
        displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));

    }
}

};

每次读取都失败,但是将值发送到特征是没有问题的。

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

解决方案是:mBluetoothGatt.readCharacteristic(mReadCharacteristic)

读完后,将调用回调。

感谢Andrew Vovk