Android accompanist-permissions 进行权限请求带跳转设置
@SuppressLint("PermissionLaunchedDuringComposition") @ExperimentalPermissionsApi @Composable fun FeatureThatRequiresPermission( permissions:MutableList<String> = mutableListOf(android.Manifest.permission.CAMERA), firstContent:String = "该权限这个应用程序很重要,请授予权限。", secondRequest:String = "需要该权限才能使用此功能,请授予权限。", lifecycle:Lifecycle, onSuccess: () -> Unit, onFail: () -> Unit, ) { val multiplePermissionsState = rememberMultiplePermissionsState(permissions) //权限是否"拒绝且不在访问" val isDenied = remember { mutableStateOf(false)} //是否在进行请求 var isRequest = false //进行请求前shouldShowRationale状态 var resumeShouldShowRationale = false class AppLifeObserver: LifecycleEventObserver { override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { when (event){ Lifecycle.Event.ON_RESUME -> if(isRequest){ isDenied.value = resumeShouldShowRationale == multiplePermissionsState.shouldShowRationale isRequest = false } else -> {} } } } lifecycle.addObserver(AppLifeObserver()) when (multiplePermissionsState.allPermissionsGranted) { true -> { onSuccess() } false -> { Dialog(onDismissRequest = {}) { var textToShow ="" var textToTip ="" var textToGo ="" resumeShouldShowRationale = multiplePermissionsState.shouldShowRationale if(isDenied.value){ textToShow = secondRequest textToTip = "取消前往" textToGo = "前往设置" } else if ( resumeShouldShowRationale) { textToShow = firstContent textToTip = "取消许可" textToGo = "请求许可" }else { runBlocking { launch { delay(100) multiplePermissionsState.launchMultiplePermissionRequest() isRequest = true } } } Column( horizontalAlignment=Alignment.CenterHorizontally, modifier = Modifier .fillMaxWidth().height(120.dp) .clip(RoundedCornerShape(5.dp)) .background(Color.hsv(0f, 0f, 1f, if(textToShow=="") 0f else 0.3f)) .padding(25.dp, 5.dp) ) { Text(textToShow, color = Color.White, modifier = Modifier.padding(10.dp)) Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) { Box(modifier = Modifier.fillMaxWidth(0.5f), contentAlignment = Alignment.CenterStart) { TextButton( onClick = { onFail() }) { Text(textToTip, color = Color.White) } } Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd) { TextButton( onClick = { if(isDenied.value) { val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) intent.data = Uri.fromParts("package", App.context.packageName, null) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) App.context.startActivity(intent) //为了跳转设置时回来重新检查权限 resumeShouldShowRationale = true } else { multiplePermissionsState.launchMultiplePermissionRequest() } isRequest = true }) { Text( text = textToGo , color = Color.Red) } } } } } } } }