dv_
dv_

Reputation: 1297

How to require different permissions in annotation depending on Android version

I have a function in a custom library that requires the BLUETOOTH_SCAN and BLUETOOTH_CONNECT permissions. Starting with Android 12, I can't just rely on adding them to the manifest XML - runtime checks are also required then.

I added the RequiresPermission annotation to my function, like this:

@RequiresPermission(allOf = [Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT])
fun myFunction()

However, I get this warning:

Field requires API level 31 (current min is 28): android.Manifest.permission#BLUETOOTH_SCAN

I set the min SDK version to 28 on purpose. But now I am stuck. for Android 12 and newer, I need the annotation to emphasize that callers check for those permissions (in other words, I want there to be a warning if callers use my function without a permission check). for Android 11 and older, the annotation must not be present? How do I solve this? I know that RequiresPermission has a conditional argument, but I do not know how to use this for this purpose. I tried to instead use BLUETOOTH and BLUETOOTH_ADMIN permissions in the annotation, but Android Studio still complains that the Bluetooth APIs that are internally used in the function need to be surrounded by permission checks.

Upvotes: 4

Views: 839

Answers (1)

Javier Refuerzo
Javier Refuerzo

Reputation: 399

You could annotate android version like the following (for example only, this is a different permission request)

    @RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
    @RequiresPermission(allOf = {Manifest.permission.POST_NOTIFICATIONS})

Although I find it easier to read and debug later by having all versions call the request permission function then return early if the version is too low

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
  return
}
//continue to ask for permission

Upvotes: 1

Related Questions