Arnyminer Z
Arnyminer Z

Reputation: 6083

New `onCharacteristicRead` method not working

after an embarrassing amount of time I have just found out that the new recommended receiver for onCharacteristicRead in BluetoothGattCallback as seen in the Android Developers reference:

public void onCharacteristicRead (BluetoothGatt gatt, 
                BluetoothGattCharacteristic characteristic, 
                byte[] value, 
                int status)

doesn't receive any data when I call readCharacteristic on the service. However, the deprecated one (Google Developers) does in fact receive the callback.

I have been following all the steps in the official guide, but trying to implement the new methods, and this is the only one so far that doesn't work in the "new callbacks".

Any ideas on how to fix this? I will use the deprecated method, but that's not something I'm keen on. Thanks in advance.

Upvotes: 13

Views: 3511

Answers (2)

mxkmn
mxkmn

Reputation: 543

When using compileSdk 33 there is a separation - on Android 13 a new function is called, on Android 12 and below a Deprecated one. To add support for older Android versions just add this to your code:

@Suppress("DEPRECATION")
@Deprecated(
    "Used natively in Android 12 and lower",
    ReplaceWith("onCharacteristicRead(gatt, characteristic, characteristic.value, status)")
)
override fun onCharacteristicRead(
    gatt: BluetoothGatt,
    characteristic: BluetoothGattCharacteristic,
    status: Int
) = onCharacteristicRead(gatt, characteristic, characteristic.value, status)

Some other functions require the same changes:

@Suppress("DEPRECATION")
@Deprecated(
    "Used natively in Android 12 and lower",
    ReplaceWith("onCharacteristicChanged(gatt, characteristic, characteristic.value)")
)
override fun onCharacteristicChanged(
    gatt: BluetoothGatt,
    characteristic: BluetoothGattCharacteristic
) = onCharacteristicChanged(gatt, characteristic, characteristic.value)

Upvotes: 1

Martijn van Welie
Martijn van Welie

Reputation: 754

The new api's are only available as of Android 13.

So

  • Make sure your phone is on Android 13
  • Set "compileSdkVersion 33" in your build.gradle
  • Set "targetSdkVersion 33" in your builld.gradle

After that, it shouuld work. At least it did for me...

Upvotes: 8

Related Questions