0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

複数種類のパーミッションを取得する

Posted at

はじめに

今回は、外部ストレージへのアクセスを加味した複数種類のパーミッションを実装していきます

実装

// ファイルアクセス用の設定画面に遷移させる処理
private fun intentManageExternalStoragePermission(context: Context) {
    val intent = Intent(
        ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
        Uri.parse("package:${context.packageName}")
    )
    intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
    context.startActivity(intent)
}
// 取得したいパーミッションの一覧を作成する
private fun createPermissions(): List<String> {
    // bluetoothのパーミッションはバージョンによって異なるのでわける
    val bluetoothPermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        listOf(
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
        )
    } else {
        listOf(Manifest.permission.BLUETOOTH)
    }
    val permissions = mutableListOf(
        Manifest.permission.CAMERA,
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    ).zip(bluetoothPermission).flatMap { it.toList() }
    return permissions
}
// 外部ストレージへのアクセス権限があるかどうかを判定するための変数
private val isExternalStorageManager: Boolean
    get() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return true
        return Environment.isExternalStorageManager()
    }

// パーミッション申請を表示させるためのUI
@OptIn(ExperimentalPermissionsApi::class)
@Composable
private fun PermissionContent(
    onAlreadyGranted: () -> Unit,
    onDenied: () -> Unit,
) {
    val context = LocalContext.current

    // 単数の場合はrememberPermissionStateでよい
    val permissionStates = rememberMultiplePermissionsState(createPermissions()) { result ->
        if (result.values.all { it } && isExternalStorageManager) {
            onAlreadyGranted()
        } else {
            onDenied()
        }
    }
    LaunchedEffect(Unit) { if (!isExternalStorageManager) intentManageExternalStoragePermission(context) }
    SideEffect { permissionStates.launchMultiplePermissionRequest() }
}

さいごに

扱うバージョンが広ければ広いほど判定も多くなりますし、新しければ新しいほど厳しくなっていくのでパーミッション周りはなかなか難しいですよね。
あまりJetpackComposeでの記事が見当たらなかったので備忘録として書いてみました
どなたかのお役に立てれば幸いです

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?