Permission Handling | Android Studio | Java

Single & Multiple Runtime Permissions

As we know we need to request Runtime Permissions on Android 6.0 (API level 23 also known as Marshmallow) and above as well as to declare them in the AndroidManifest file.  If we need to use some features like Camera, Location, Contact, etc. we have to handle the runtime permissions. In this Tutorial, we will learn how to Request Single and Multiple Permissions.

Note: I'll add some permissions for example purposes only you may apply the same on permissions you want.

>>Check For Kotlin

Video:

Code:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <!--For Single Permission Example-->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <!--For Multiple Permission Example-->
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.CALL_PHONE"/>

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.PermissionHandling"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp"
    android:gravity="center"
    tools:context=".MainActivity">

    <!--TextView: Just for label-->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Permission handling"
        style="@style/TextAppearance.MaterialComponents.Headline4"/>

    <!--MaterialButton: Click to request single permission-->
    <com.google.android.material.button.MaterialButton
        android:id="@+id/singlePermissionBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Single Permission Request"
        android:layout_marginTop="20dp"/>

    <!--MaterialButton: Click to request multiple permissions-->
    <com.google.android.material.button.MaterialButton
        android:id="@+id/multiplePermissionBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Multiple Permission Request"/>

    <!--TextView: Show result of permission request-->
    <TextView
        android:id="@+id/resultTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Result"/>

</LinearLayout>

MainActivity.java

package com.technifysoft.permissionhandling;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.button.MaterialButton;

import java.util.Map;

public class MainActivity extends AppCompatActivity {

    //UI Views
    private MaterialButton singlePermissionBtn;
    private MaterialButton multiplePermissionBtn;
    private TextView resultTv;


    private static final String TAG = "PERMISSION_TAG";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //init the UI Views
        singlePermissionBtn = findViewById(R.id.singlePermissionBtn);
        multiplePermissionBtn = findViewById(R.id.multiplePermissionBtn);
        resultTv = findViewById(R.id.resultTv);

        //handle singlePermissionBtn click, check and request single permission before doing the task that requires it
        singlePermissionBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //permission to be requested
                String permission = Manifest.permission.ACCESS_FINE_LOCATION;
                //launcher permission request dialog
                permissionLauncherSingle.launch(permission);
            }
        });

        //handle multiplePermissionBtn click, check and request multiple permissions before doing the task that requires it
        multiplePermissionBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //permissions to be requested
                String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.CALL_PHONE};
                //launcher permissions request dialog
                permissionLauncherMultiple.launch(permissions);
            }
        });
    }

    private ActivityResultLauncher<String> permissionLauncherSingle = registerForActivityResult(
            new ActivityResultContracts.RequestPermission(),
            new ActivityResultCallback<Boolean>() {
                @Override
                public void onActivityResult(Boolean isGranted) {
                    //here we will check if permission was now (from permission request dialog) or already granted or not. the param isGranted contains value true/false
                    Log.d(TAG, "onActivityResult: isGranted: " + isGranted);

                    if (isGranted) {
                        //Permission granted now do the required task here or call the function for that
                        singlePermissionGranted();
                    } else {
                        //Permission was denied so can't do the task that requires that permission
                        Log.d(TAG, "onActivityResult: Permission denied...");
                        Toast.makeText(MainActivity.this, "Permission denied...", Toast.LENGTH_SHORT).show();
                    }
                }
            }
    );

    private ActivityResultLauncher<String[]> permissionLauncherMultiple = registerForActivityResult(
            new ActivityResultContracts.RequestMultiplePermissions(),
            new ActivityResultCallback<Map<String, Boolean>>() {
                @Override
                public void onActivityResult(Map<String, Boolean> result) {
                    //here we will check if permissions were now (from permission request dialog) or already granted or not

                    boolean allAreGranted = true;
                    for (Boolean isGranted : result.values()) {
                        Log.d(TAG, "onActivityResult: isGranted: " + isGranted);
                        allAreGranted = allAreGranted && isGranted;
                    }

                    if (allAreGranted) {
                        //All Permissions granted now do the required task here or call the function for that
                        multiplePermissionsGranted();
                    } else {
                        //All or some Permissions were denied so can't do the task that requires that permission
                        Log.d(TAG, "onActivityResult: All or some permissions denied...");
                        Toast.makeText(MainActivity.this, "All or some permissions denied...", Toast.LENGTH_SHORT).show();
                    }
                }
            }
    );

    private void singlePermissionGranted() {
        //Do the required task here, i'll just set the text to the TextView i.e. resultTv. You can do whatever you want
        resultTv.setText("Single Permission granted. You can do your tasks...");
    }

    private void multiplePermissionsGranted() {
        //Do the required task here, i'll just set the text to the TextView i.e. resultTv. You can do whatever you want
        resultTv.setText("All Permissions granted. You can do your tasks...");
    }

}

Result:

Permission Handling | Android Studio | Java



Comments

Popular posts from this blog

Picture In Picture | Android Studio | Kotlin

Manage External Storage Permission | Android Studio | Kotlin

Add a Back Button to Action Bar Android Studio (Kotlin)