Kotlin - アプリの権限を取得する

ここでは BLUETOOTH_CONNECT 権限を例にする。

ここでは BLUETOOTH_CONNECT 権限を例にする。

権限ランチャーを作る

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// 権限ランチャー
private val requestPermissionLauncher =
    registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        if (isGranted) {
            // 権限を取得できた
            Log.i("Permission: ", "Granted")
        } else {
            // 権限を取得できなかった
            Log.i("Permission: ", "Denied")
        }
    }

権限をリクエスト

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private fun requestBluetoothPermission() {
    when {
        ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.BLUETOOTH_CONNECT
        ) == PackageManager.PERMISSION_GRANTED -> {
            bluetoothInit()
        }

        ActivityCompat.shouldShowRequestPermissionRationale(
            this,
            Manifest.permission.BLUETOOTH_CONNECT
        ) -> {
            Toast.makeText(this, "Bluetooth 権限は必要にゃ。", Toast.LENGTH_LONG).show()
            requestPermissionLauncher.launch(
                Manifest.permission.BLUETOOTH_CONNECT
            )
        }

        else -> {
            Toast.makeText(this, "Bluetooth 権限は必要にゃ。", Toast.LENGTH_LONG).show()
            requestPermissionLauncher.launch(
                Manifest.permission.BLUETOOTH_CONNECT
            )
        }
    }
}
Hugo で構築されています。
テーマ StackJimmy によって設計されています。