rememberLauncherForActivityResult() を使います。
enum class PermissionState {
Checking,
Granted,
Denied,
}
@Composable
private fun NeedPermissionScreen() {
var state by remember { mutableStateOf(PermissionState.Checking) }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) {
state = if (it) PermissionState.Granted else PermissionState.Denied
}
val permission = Manifest.permission.CAMERA
val context = LocalContext.current
val lifecycleObserver = remember {
LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_START) {
val result = context.checkSelfPermission(permission)
if (result != PackageManager.PERMISSION_GRANTED) {
state = PermissionState.Checking
launcher.launch(permission)
} else {
state = PermissionState.Granted
}
}
}
}
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle, lifecycleObserver) {
lifecycle.addObserver(lifecycleObserver)
onDispose {
lifecycle.removeObserver(lifecycleObserver)
}
}
when (state) {
PermissionState.Checking -> {
}
PermissionState.Granted -> {
// TODO パーミッションが必要な機能を使う画面
}
PermissionState.Denied -> {
// TODO 拒否された時の画面
}
}
}
追記:
Accompanist に最近 Permission のやつが追加されました (現状 Permission 関係のすべての機能は experimental)
https://google.github.io/accompanist/permissions/
0 件のコメント:
コメントを投稿