Kotlin - Android

Request Permission Launcher with Kotlin in Android

In this article, we are learning about the run time permissions for request permission launchers. As we know that onRequestPermissionsResult is deprecated in the latest android API version. So we need to use registerForActivityResult() method instead onRequestPermissionsResult() as alternative of onRequestPermissionsResult().

Let’s take an example where we need to access the camera to take pictures. First of all, you need to give use permission in your android manifest file.

<uses-permission android:name="android.permission.CAMERA" />

Single Permission Request

let’s make a permission request.

 private fun checkPermission() {
    val permission = ContextCompat.checkSelfPermission(
        requireContext(), Manifest.permission.CAMERA)

    if (permission != PackageManager.PERMISSION_GRANTED) {
        permissionsResultCallback.launch(Manifest.permission.CAMERA)
    } else {
        println("Permission isGranted")
    }
}

Once you make a request for launch permission, the android os will show the popup for permission to allow and deny option and once the user click any option then we will get the callback with the result which needs to handle.

private val permissionsResultCallback = registerForActivityResult(
    ActivityResultContracts.RequestPermission()){
    when (it) {
        true -> { println("Permission has been granted by user") }
        false -> {
            Toast.makeText(requireContext(), "Permission denied", Toast.LENGTH_SHORT).show()
            //show your custom dialog and naviage to Permission seetings 
        }
    }
}

Multiple Permission Request

Let’s take an example where we need to make multiple requests together to access the feature for example camera and microphone to record audio. First thing, these two permission should be added to android manifest file.

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
companion object {
       var PERMISSIONS = arrayOf(
           Manifest.permission.CAMERA,
           Manifest.permission.RECORD_AUDIO
       )
   }
private fun checkPermissionRequired() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        // direct navigate to respective screen
       
    }
    activity?.let {
        if (hasPermissions(activity as Context, PERMISSIONS)) {
            // direct navigate to respective screen
        } else {
            // request to launch
            permReqLauncher.launch(
                PERMISSIONS
            )
        }
    }
}

Check the permission is granted.

private fun hasPermissions(context: Context, permissions: Array<String>): Boolean = permissions.all {
        ActivityCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
    }

Now if the permission is not given then request to launch permission.

private val permReqLauncher =
       registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
           val granted = permissions.entries.all {
               it.value == true
           }
           if (granted) {
              // navigate to respective screen
           }else{
               // show custom alert
                //Previously Permission Request was cancelled with 'Dont Ask Again',
               // Redirect to Settings after showing Information about why you need the permission
               showPermissionDialog()
           }
       }

If the permission is deny by user then better to show a dialog to convince user to access the feature of the app, you need to grant these permission. And navigate to Permission settings screen to allow the user to grant this permission.

private fun showPermissionDialog() {
       val builder = AlertDialog.Builder(requireContext())
       builder.setTitle("Permission required")
       builder.setMessage("Some permissions are needed to be allowed to use this app without any problems.")
       builder.setPositiveButton("Grant") { dialog, which ->
           dialog.cancel()
           val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
           intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
           val uri = Uri.fromParts("package", requireActivity().packageName, null)
           intent.data = uri
           startActivity(intent)
       }
       builder.setNegativeButton("Cancel") { dialog, which ->
           dialog.dismiss()
       }
       builder.show()
   }

That is all for this. Thanks for reading this article.

 

4.5 2 votes
Article Rating
Request Permission Launcher with Kotlin in Android

Recent Posts

Hide your production API key or any sensitive data in Android

Hi everyone, In this article, we are going to learn how to hide the production… Read More

2 years ago

How to handle the localisation or multi language support in android with examples?

Hello everyone, Today in this article, we are going to learn about localisation to support… Read More

2 years ago

How to convert any callback to Coroutines and use them in Kotlin Android?

Hello everyone, In this article, we are going to learn something to handle the callback… Read More

2 years ago

Implement the SMS User Consent API and SMS Retriever API in Android

Hello everyone. In my last tutorial, we learned about the Jetpack Compose introduction and about applying the… Read More

3 years ago

Jetpack Compose Coroutine flow with LiveData/ViewModel in Android

Hello everyone, In this article, we are going to learn about the Jetpack Compose with… Read More

3 years ago

Android Jetpack Compose of layouts, row, column, modifier, ConstraintLayout and Scaffold

Hello everyone, In this article, we are going to learn how to use layouts, rows,… Read More

3 years ago