Modern way of requesting Permission in Android

Maheshchakkarwar
2 min readMay 12, 2022

--

Why we need permission in Android?

Every Android app runs in its own sandbox. But, if application wants access to outer resources, it needs permission.

What are the ways of requesting permission?

It depends on OS on which application runs.

  1. On Android 5.1 (API level 22) and below : User needs to declare permission in manifest as uses-permission. For example,
    <uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION”/>
  2. Android 6.0 (API level 23) or higher : Application must request permission at runtime. In this case also application needs to declare permission in manifest.

How to check user has granted permission or not?

Let’s consider application want access to location.

if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
//Write code to request permission
}

What is best way of requesting permission in Android?

Best way to request permission is to use jetpack androidX framework. I will explain step by step for requesting location permission.

  1. Add permission in manifest as we used to do for Android API 22 and below. For example,
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

2. Add dependency in build.gradle file

dependencies {
implementation 'androidx.activity:activity-ktx:1.4.0'
}

3. Add below code in onAttach() or onCreate() of activity lifecycle

val requestPermissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) {
if
(it) {
//Permission granted by user. Access the required resources here
} else {
//Permission denied by user
}
}
requestPermissionLauncher.launch(ACCESS_FINE_LOCATION)

registerForActivityResult two parameters;

  1. ActivityResultContract : ActivityResultContracts provides some contracts you can use directly like StartActivityForResult, StartIntentSenderForResult, RequestMultiplePermissions, RequestPermission, TakePicturePreview, TakePicture, TakeVideo etc. Also, you can implement your ActivityResultContract by inheriting abstract class ActivityResultContract and provide implementation for creating intent and parsing result to return desired output.
  2. Callback : You need to implement callback to handle users action on permission dialog like granted permission or denied permission.

--

--

Maheshchakkarwar

A enthusiastic Android Developer like to learn new things and share to everyone.