Skip to content
DeveloperMemos

Permissions in Android: Requesting Permissions and Handling User Responses

Permissions, Requesting Permissions, User Responses1 min read

To start off with the bare basics - to request permissions in Android, you need to add the relevant permission(s) to your app's manifest file. For example, to request permission to use the camera, you would add the following line to your AndroidManifest.xml:

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

Once you've added the necessary permissions to the manifest file, you can then request them at runtime using the requestPermissions() method. Here's an example of how to request permission to use the camera:

1private val CAMERA_PERMISSION_CODE = 1
2
3if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
4 == PackageManager.PERMISSION_DENIED) {
5 ActivityCompat.requestPermissions(
6 this,
7 arrayOf(Manifest.permission.CAMERA),
8 CAMERA_PERMISSION_CODE
9 )
10}

In this example, we're checking if the app has permission to use the camera. If it doesn't, we're requesting permission using the requestPermissions() method. This method takes three parameters:

  • The activity or fragment making the request.
  • An array of permission strings to be requested.
  • A request code that identifies this particular request.

When you call requestPermissions(), Android will display a system dialog asking the user to grant or deny the requested permission(s). The user can choose to grant or deny the permission(s) at this point.

Handling User Responses

After the user has granted or denied permission, your app will receive a callback in the onRequestPermissionsResult() method. Here's an example of how to handle the user's response:

1override fun onRequestPermissionsResult(
2 requestCode: Int,
3 permissions: Array<String>,
4 grantResults: IntArray
5) {
6 when (requestCode) {
7 CAMERA_PERMISSION_CODE -> {
8 if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
9 // Permission granted, do something with the camera.
10 } else {
11 // Permission denied, show a message to the user.
12 }
13 return
14 }
15 }
16}

In this example, we're checking if the user granted permission to use the camera. If permission is granted, we can proceed to use the camera. If permission is denied, we can show a message to the user explaining why we need the permission and ask them to grant it manually through the device settings.

Wrap Up

In closing, requesting permissions and handling user responses is an essential part of developing Android apps. By following the steps outlined in this article, you can ensure that your app requests the necessary permissions and handles the user's response appropriately.