Skip to main content

Kotlin - Obtaining App Permissions

·99 words
icysamon
Author
icysamon
Electronics & Creator

Here, we’ll use the BLUETOOTH_CONNECT permission as an example.

Creating a Permission Launcher
#

// Permission launcher
private val requestPermissionLauncher =
    registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        if (isGranted) {
            // Permission granted
            Log.i("Permission: ", "Granted")
        } else {
            // Permission denied
            Log.i("Permission: ", "Denied")
        }
    }

Requesting Permission
#

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, "I need Bluetooth permission.", Toast.LENGTH_LONG).show()
            requestPermissionLauncher.launch(
                Manifest.permission.BLUETOOTH_CONNECT
            )
        }

        else -> {
            Toast.makeText(this, "Bluetooth permission is required, meow.", Toast.LENGTH_LONG).show()
            requestPermissionLauncher.launch(
                Manifest.permission.BLUETOOTH_CONNECT
            )
        }
    }
}