How to use Permissions in Android in an Android app?

In Android, permissions are crucial for ensuring that apps only access the data and features that they need, while also protecting users' privacy. Starting from Android 6.0 (API level 23), permissions are categorized into two types: normal and dangerous. Normal permissions are granted automatically, while dangerous permissions require explicit user consent at runtime.

Requesting Permissions

To request permissions in your Android app, you need to add the necessary permissions to your AndroidManifest.xml file and then check and request them at runtime if they fall under the dangerous category.

Step 1: Add Permissions in AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">
    
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        ...
    >
        ...
    </application>
</manifest>
    

Step 2: Check and Request Permissions at Runtime


// Check if the permission is granted
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
        != PackageManager.PERMISSION_GRANTED) {
    // Permission is not granted, request it
    ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.CAMERA},
            REQUEST_IMAGE_CAPTURE);
} else {
    // Permission has already been granted
    openCamera();
}
    

Step 3: Handle the permission request response


@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == REQUEST_IMAGE_CAPTURE) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission granted
            openCamera();
        } else {
            // Permission denied
            Toast.makeText(this, "Camera permission denied", Toast.LENGTH_SHORT).show();
        }
    }
}
    

By following these steps, you can effectively manage permissions in your Android application.


Android permissions runtime permissions AndroidManifest.xml check permissions request permissions