Android Working With App Permission In Java

The Word Permission means allowing sometime , to do a particular thing – it is consent or authorization given to perform any kind of action , Android apps are built to perform a set of actions, some of them requiring permissions from users .

With the introduction of Android 6.0 Marshmallow, Google has changed the way permissions are handled by the app , Before Marshmallow all permissions are granted by the system automatically .


From Marshmallow Android Permissions are divided into dangerous and normal Permission , The common thing in both the types is that they need to be defined in the Manifest file. 
  1. Normal Permission. 
  2. Runtime Permission ( Dangerous Permission ).

1. Normal Permission : 

  • These permissions allow access to data and actions that extend beyond your app's sandbox.
  • The system grants these permissions automatically
  • Poses Low or No Risk .
  • These include connecting to the internet, getting network, Bluetooth, wifi, and NFC information, setting alarms & wallpapers, and modifying audio settings on a device
  

2. Runtime Permission : 

  • Dangerous permissions are permissions which could potentially affect the user’s privacy or the device’s operation .
  • The user must explicitly agree to grant those permissions. 
  • Poses High Risk .
  • These include accessing the camera, contacts, location, microphone, sensors, SMS, and storage.


1. Declaring Permissions Needed by Your App In Apps Manifest


Add Permission to manifest . 

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

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
	   ------------>
        -----------
         ----------		
    </application>

</manifest>

2. Check is Permission Granted


Before Making Request check is Permission already granted .

private boolean checkPermissionForReadExtertalStorage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            return ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        }
        return false;
    }

3. Requesting Permissions for Your App


Making Request for Permission by Passing request code .
 private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_WRITE_PERMISSION);
        }
    }

4. Handling Permissions Granted to Your App


Override the onRequestPermissionsResult callback of AppCompatActivity Inside this we will get to know the status of requested permission .

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (grantResults.length > 0) {
            if (requestCode == REQUEST_WRITE_PERMISSION)
                if (grantResults[0]
                        == PackageManager.PERMISSION_GRANTED) {
                    // permission granted
                    label.setText(R.string.permission_granted);
                } else {
                    // permission denied
                    label.setText(R.string.permission_denied);
                }
        }
    }


Main Activity


Complete MainActivity Code .

file : MainActivity.java 
package com.tutorialsbuzz.permissionexample;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

    public static final int REQUEST_WRITE_PERMISSION = 100;
    private TextView label;

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

        label = findViewById(R.id.label);

        Button requestBtn = findViewById(R.id.requestBtn);
        requestBtn.setOnClickListener(v -> {
            if (checkPermissionForReadExtertalStorage()) {
                // Permission Already Granted
                label.setText(R.string.permission_granted);
            } else {
                // Make Permission Request
                requestPermission();
            }
        });

    }

    private boolean checkPermissionForReadExtertalStorage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            return ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        }
        return false;
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_WRITE_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (grantResults.length > 0) {
            if (requestCode == REQUEST_WRITE_PERMISSION)
                if (grantResults[0]
                        == PackageManager.PERMISSION_GRANTED) {
                    // permission granted
                    label.setText(R.string.permission_granted);
                } else {
                    // permission denied
                    label.setText(R.string.permission_denied);
                }
        }
    }

}


No comments:

Post a comment