How to Check and Request for Permissions at Runtime
How to Check and Request Runtime Permissions in Android.
In Android, permissions are used to protect sensitive information or features of an app. These permissions must be declared in the AndroidManifest.xml file. However, starting from Android Marshmallow (API level 23), app developers need to request permissions at runtime when the app is running. This article will guide you through the process of checking and requesting runtime permissions in your Android app.
Step 1: Declare the Permissions in AndroidManifest.xml
Before you can request permissions at runtime, you need to declare the permissions you want to use in your app. You can declare permissions in the AndroidManifest.xml file using the <uses-permission> element. For example, if you want to use the camera in your app, you can declare the CAMERA permission like this:
<uses-permission android:name="android.permission.CAMERA" />
It's important to note that not all permissions require runtime permission requests. Some permissions are considered "normal" and are automatically granted to the app. These include permissions like INTERNET, VIBRATE, and ACCESS_NETWORK_STATE.
Step 2: Check if the Permission is Granted
Before you can use a feature that requires a permission, you need to check if the permission is granted. You can do this by calling the checkSelfPermission() method of the ContextCompat class. For example, to check if the CAMERA permission is granted, you can do this:
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
// Permission is granted, proceed to use the camera
} else {
// Permission is not granted, request it at runtime
}
If the permission is granted, you can proceed to use the feature that requires it. Otherwise, you need to request the permission at runtime.
Step 3: Request the Permission at Runtime
To request a permission at runtime, you need to call the requestPermissions() method of the ActivityCompat class. This method takes an array of permissions to request and a request code that will be used to identify the request. For example, to request the CAMERA permission, you can do this:
ActivityCompat.requestPermissions(
this,
arrayOf(android.Manifest.permission.CAMERA),
MY_PERMISSIONS_REQUEST_CAMERA
)
The MY_PERMISSIONS_REQUEST_CAMERA constant is a request code that you can define in your app to identify the request.
Step 4: Handle the Permission Result
After requesting the permission, the user will be prompted to grant or deny the permission. Once the user has made a decision, the onRequestPermissionsResult() method of your activity will be called. You need to override this method to handle the permission result. For example, to handle the CAMERA permission request result, you can do this:
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
when (requestCode) {
MY_PERMISSIONS_REQUEST_CAMERA -> {
if (grantResults.isNotEmpty() &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted, proceed to use the camera
} else {
// Permission is denied, show a message or disable the feature
}
return
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
In this example, if the CAMERA permission is granted, you can proceed to use the camera. Otherwise, you can show a message or disable the feature that requires the permission.
More
Due to security reasons, android operating system restricts access to some resources untill the user explicitly grants you access to these. So if you want to use these, for example connect to internet or read external storage, then you need to first check if you have the necessary permissions otherwise request them.
This piece will help you with this using beginner friendly examples. Step by step you will learn how to:
- Check for Permissions
- Request Permissions.
Example 1 - Create a simple app to check for permissions then request them
This example is a single activity example that teaches you how to check for permissions then request it.
Step 1: Add Dependencies
In this case no special dependency is needed.
Step 2: Design Layouts
You will find a simpl e layout in the source code.
Step 3: Write Code
Make your main activity implement the onClickListener interface:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Then in the activity define two instance fields, one a permission request code and the other a view object:
private static final int PERMISSION_REQUEST_CODE = 200;
private View view;
Then create a method called checkPermission() like below that will check for permission:
private boolean checkPermission() {
//int result = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);
return result1 == PackageManager.PERMISSION_GRANTED;
}
For example the above method allows you to check for camera permission. The commented line would allow you check for fine location permission.
Then create a method to request the permission. You use the requestPermissions() method of the ActivityCompat class:
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, PERMISSION_REQUEST_CODE);
}
Now override the onRequestPermissionsResult method as below:
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0) {
// boolean locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean cameraAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted)
Snackbar.make(view, "Permission Granted, Now you can access camera.", Snackbar.LENGTH_LONG).show();
else {
Snackbar.make(view, "Permission Denied, You cannot access camera.", Snackbar.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)) {
showMessageOKCancel("You need to allow access to the permission",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{ACCESS_FINE_LOCATION, CAMERA},
PERMISSION_REQUEST_CODE);
}
}
});
return;
}
}
}
}
break;
}
Full Code
Here is the full code, there is only one activity:
MainActivity.java
package com.example.ankitkumar.permissionrequest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.CAMERA;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static final int PERMISSION_REQUEST_CODE = 200;
private View view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button check_permission = (Button) findViewById(R.id.check_permission);
Button request_permission = (Button) findViewById(R.id.request_permission);
check_permission.setOnClickListener(this);
request_permission.setOnClickListener(this);
}
@Override
public void onClick(View v) {
view = v;
int id = v.getId();
switch (id) {
case R.id.check_permission:
if (checkPermission()) {
Snackbar.make(view, "Permission already granted.", Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(view, "Please request permission.", Snackbar.LENGTH_LONG).show();
}
break;
case R.id.request_permission:
if (!checkPermission()) {
requestPermission();
} else {
Snackbar.make(view, "Permission already granted.", Snackbar.LENGTH_LONG).show();
}
break;
}
}
private boolean checkPermission() {
//int result = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);
return result1 == PackageManager.PERMISSION_GRANTED;
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, PERMISSION_REQUEST_CODE);
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0) {
// boolean locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean cameraAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted)
Snackbar.make(view, "Permission Granted, Now you can access camera.", Snackbar.LENGTH_LONG).show();
else {
Snackbar.make(view, "Permission Denied, You cannot access camera.", Snackbar.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)) {
showMessageOKCancel("You need to allow access to the permission",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{ACCESS_FINE_LOCATION, CAMERA},
PERMISSION_REQUEST_CODE);
}
}
});
return;
}
}
}
}
break;
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
}
Reference
Find reference links below:
| No. | Link |
|---|---|
| 1. | Download Example |
| 2. | Follow Code Author |
Conclusion
In this article, we have learned how to check and request runtime permissions in Android. We have seen how to declare permissions in the AndroidManifest.xml file, how to check if a permission is granted, how to request a permission at runtime, and how to handle the permission result. By following these steps, you can ensure that your app is secure and respects the user's privacy.