Android Compose 权限请求

Ghlerrix2022/08/12androidandroid

在Compose中以往的权限请求方式就不再适用了。因此我在使用过程中发现了一种非常简单优雅的权限申请方法。

全部代码见Github Shanyaliux/ComposeDemo (github.com)open in new window

实现

权限请求

  • Activity中添加一下请求方法

    private fun requestPermissions(permissions: Array<String>, onResult: (List<String>) -> Unit) {
            registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
                val failed = result.filter { !it.value }.keys
                onResult(failed.toList())
            }.launch(permissions)
        }
    
  • 请求权限,改写onCreate的部分代码如下

    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            val requestList =
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
    
            requestPermissions(requestList) {
                setContent {
                    if (it.isEmpty()) {
                        Text(text = "已获取全部权限.")
                    } else {
                        RequestFailedDialog(it)
                    }
                }
            }
        }
    

    注意

    别忘了在Manifest文件中先声明权限

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    

请求失败对话框提示(可选)

@Composable
fun RequestFailedDialog(permissions: List<String>) {
    val activity = LocalContext.current as? Activity
    AlertDialog(onDismissRequest = {  },
        buttons = {
            Row {
                Button(
                    onClick = {
                        activity?.finish()
                    },
                    modifier = Modifier.weight(1f,true),
                    shape = RoundedCornerShape(bottomStart = 8.dp),
                    colors = ButtonDefaults.buttonColors(backgroundColor = Color.White),
                ) {
                    Text(text = "取消")
                }
                Button(
                    onClick = {
                        val intent = Intent()
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                        intent.data = Uri.fromParts("package", activity?.packageName, null)
                        activity?.startActivity(intent)
                    },
                    modifier = Modifier.weight(1f,true),
                    shape = RoundedCornerShape(bottomEnd = 8.dp),
                    colors = ButtonDefaults.buttonColors(backgroundColor = Color.White),
                ) {
                    Text(text = "确定")
                }
            }
        },
        title = {
            Text(text = "提示")
        },
        text = {
            Surface {
                LazyColumn() {
                    items(permissions) { permission ->
                        Text(text = permission)
                    }
                }
            }
        },
        shape = RoundedCornerShape(8.dp),
        backgroundColor = Color.White,
        contentColor = Color.Black,
        properties = DialogProperties()

    )
}

Demo

完整Demo代码见GitHub:ComposeDemo/app/src/main/java/cn/shanyaliux/composedemo/permission at master · Shanyaliux/ComposeDemo (github.com)open in new window

截图

https://cdn.jsdelivr.net/gh/Shanyaliux/PicBed/img/image-20220812224844049.png

https://cdn.jsdelivr.net/gh/Shanyaliux/PicBed/img/image-20220812225142494.png

参考

https://icode.best/i/68552745363490open in new window

最后更新时间 11/21/2024, 2:02:30 PM