如何在 Jetpack Compose 中请求权限?

Two*_*ses 1 android kotlin android-jetpack-compose

我有一个需要在运行时请求权限的应用程序。
我进行了搜索,但找不到有关如何在 Jetpack Compose 中执行此操作的解决方案。

如何在运行时从@Composable函数请求/检查权限?(我的函数嵌套得很深,所以我无法访问活动实例)

我想要这样的东西:

@Composable()
fun test() {
  val hasPermission = checkPermission("READ_CONTACTS")
  if (hasPermission)
    LoadData()
  else
    requestPermission("READ_CONTACTS")
}
Run Code Online (Sandbox Code Playgroud)

Gab*_*tti 8

1.3.0-alpha06 从开始,androidx.activity:activity-compose您可以使用rememberLauncherForActivityResult向 注册请求Activity#startActivityForResult

就像是:

val launcher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        if (isGranted) {
            // Permission Accepted 
        } else {
            // Permission Denied 
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后就可以使用它:

val context = LocalContext.current

Button(
    onClick = {
        
        when {
            //Check permission
            ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_GRANTED -> {
                // You can use the API that requires the permission.

            } else -> {
                 // Asking for permission
                 launcher.launch(Manifest.permission.CAMERA)
            }
        }
    }
) {
    Text(text = "Button")
}
Run Code Online (Sandbox Code Playgroud)

  • 如何一次请求多个权限? (2认同)