Characteristics of Android BLE getValue returns null

I am trying to write text data to my BLE device. So, I follow the Bluetooth Bluetooth GATT classes to complete this task. But I found that writing the text in the properties is great, but when I try to get the "Values" value, it returns null.

MyCode:

public void writeCharacteristic(BluetoothGattCharacteristic characteristic,
                                String text) {

    String TAGS ="MyBeacon";

    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAGS, "BluetoothAdapter not initialized");
        return;
    } else {
        Log.w(TAGS, "Writting ... ");
    }
    byte[] data = hexStringToByteArray(text);


    Log.w(TAGS, "Writting text = " + data);


    try {
        characteristic.setValue(URLEncoder.encode(text, "utf-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    boolean writeValue = mBluetoothGatt.writeCharacteristic(characteristic);

    Log.w(TAGS, "Writting Status = " + writeValue);

}

// Successfully onCharacteristicWrite also gets called //

   @Override
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicWrite(gatt, characteristic, status);

        String TAGS ="MyBeacon";

        String text = null;
        try {
            text = new String(characteristic.getValue(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Log.w(TAGS, "onCharacteristicWrite = " + text+" :: "+status);

    }

but when trying to read the characteristics, it returns null.

  for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {

                final byte[] data = gattCharacteristic.getValue(); // returns null

                  if (data != null && data.length > 0) {

                     Log.d("MyBeacon", " Read Data ")

                  } else {

                     Log.d("MyBeacon", " Data is null")
                  }

      }

Mybeacon

Also check the problem in another thread.

Please help me, offer me some solution for writing and reading data on my beacon.

+4
source share
2 answers

The syntax should be as follows:

mBluetoothGatt.readCharacteristic(characteristic);

: , mBluetoothGatt.readCharacteristic(characteristic);

:

mBluetoothGatt.readDescriptor(ccc);

, , onDescriptorRead. () , :

mBluetoothGatt.setCharacteristicNotification(characteristic, true)

, true, ( )

BluetoothGattDescriptor clientConfig = characteristic.getDescriptor(CCC);
clientConfig.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);

//clientConfig.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
mBluetoothGatt.writeDescriptor(clientConfig);

, onCharacteristicChanged , .

, ,

+2

? , onCharacteristicWrite().

0

All Articles