Casper Bang
Casper Bang

Reputation: 579

How to use Compose Accompanist to work with new permissions on old devices?

Using Jetpack Compose Permissions from the Accompanist Permission library (https://google.github.io/accompanist/permissions/) is a nice reactive way. However, it's unclear to me how to deal with permissions which depend on the OS version its being used on.

For instance, the opt-out for notification changed with Android Tiramisu/33 så that it's now opt-in using POST_NOTIFICATIONS permission. The question then is, how do you use

val permissionState: PermissionState = rememberPermissionState(
        permission = Manifest.permission.POST_NOTIFICATIONS
    )

...when the POST_NOTIFICATIONS API can't be referenced on say Android 9. The only workaround I can think of, which feels like a hack, is to fall-back to some other permission which is auto-granted by default i.e. the INTERNET permission. Like so:

val permissionState: PermissionState = rememberPermissionState(
        permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
            Manifest.permission.POST_NOTIFICATIONS else Manifest.permission.INTERNET
    )

Is there a better solution than the one mentioned above?

Upvotes: 4

Views: 1783

Answers (2)

Djé
Djé

Reputation: 51

What about a dummy, always granted, fall-back PermissionState ?

val permittedState = object : PermissionState {
    override val permission: String = ""
    override val status: PermissionStatus = PermissionStatus.Granted
    override fun launchPermissionRequest() { }
}

val permissionState = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    rememberPermissionState(Manifest.permission.POST_NOTIFICATIONS) } else permittedState

It allows to deal with this permission, which depend on the OS version it's being used on, without:

  • Introducing another permission which may not be necessary for the application but would require to be declared in the Manifest
  • Adding the unnecessary complexity of a MultiplePermissionsState

On versions targeted by the permission, the rememberPermissionState will do its job as expected, while on others, the permission checks usingpermissionState.status.isGranted (see the link provided in the question) will always return true.

Upvotes: 1

Derek K
Derek K

Reputation: 3197

There is a better workaround:

 val permissionState = rememberMultiplePermissionsState(
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        listOf(Manifest.permission.POST_NOTIFICATIONS)
    } else {
        // permission not needed
        emptyList()
    }
 )

Upvotes: 3

Related Questions