Android Runtime Permissions


Introduction

In many android applications nowadays we can get to see the application asks for permission to use a specific feature during runtime. For example the application which uses a device camera asks for camera permission during the runtime of the application, from that user can provide or reject the permission. In this article we will take a look on How to add Runtime permissions within our android application.

Implementation

We will be creating a simple application in which we will be creating a text view for displaying the heading of our application. After that we are creating a button which is used to request the permissions. For this application we will be requesting permission to read SMS within our android device.

Step 1 : Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note − Make sure to select the Language as Java.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.java file.

Step 2 : Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
   tools:context=".MainActivity">

   <!-- creating a text view on below line-->
   <TextView
       android:id="@+id/idTVMessage"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_above="@id/idBtnRequestPermissions"
       android:layout_margin="20dp"
       android:padding="4dp"
       android:text="Android Runtime Permissions"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="23sp"
       android:textStyle="bold" />
   <!-- creating a button for displaying a short message -->
   <Button
       android:id="@+id/idBtnRequestPermissions"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_centerInParent="true"
       android:layout_marginStart="10dp"
       android:layout_marginTop="10dp"
       android:layout_marginEnd="10dp"
       android:layout_marginBottom="10dp"
       android:text="Request SMS Permissions"
       android:textAllCaps="false" />
</RelativeLayout>

Explanation: In the above code we are creating a root layout as a Relative Layout. Inside this layout we are creating a text view which is used to display the heading of our application. After that we are creating a button which we will use to request permission for reading SMS on mobile devices.

Step 3: Adding permissions in AndroidManifest.xml file

Navigate to app>AndroidManifest.xml file and add below permissions to it in manifest tag to read sms.

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

Step 4: Working with MainActivity.java file

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>MainActivity.java to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.example.java_test_application;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {
   // creating variables on below line for button.
   private Button permissionsBtn;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       // initializing variables on below line.
       permissionsBtn = findViewById(R.id.idBtnRequestPermissions);
       // on below line adding click listener for short message button.
       permissionsBtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // on below line we are checking the self permissions for reading sms.
               if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_DENIED) {
                   // if permission is not granted then we are requesting for the permissions on below line.
                   ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_SMS}, 100);
               } else {
                   // if permission is already granted then we are displaying a toast message as permission granted.
                   Toast.makeText(MainActivity.this, "Permission already granted", Toast.LENGTH_SHORT).show();
               }
           }
       });
   }

   @Override
   public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
       super.onRequestPermissionsResult(requestCode, permissions, grantResults);
       // on below line we are checking for the request code.
       if (requestCode == 100) {
           // on below line we are checking if permissions are granted.
           if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               // displaying a toast message when permission is granted.
               Toast.makeText(MainActivity.this, "Read SMS Permission Granted", Toast.LENGTH_SHORT).show();
           } else {
               // displaying a toast message when permission is denied.
               Toast.makeText(MainActivity.this, "Read SMS Permission Denied", Toast.LENGTH_SHORT).show();
           }
       }
   }
}

Explanation: In the above code firstly we are creating variables for our button. Now we will get to see the onCreate method. This is the default method of every android application. This method is called when the application view is created. Inside this method we are setting the content view i.e the layout file named activity_main.xml to set the UI from that file. Inside the onCreate method we are initializing the button variable with the id which we have given in our activity_main.xml file. After that we are adding an on click listener for both buttons. Inside the on click listener we are firstly checking if the permission is already granted. If the permission is granted we are displaying a toast message as permission granted. If the permission is not granted then we are requesting permission to read sms. Now we are creating one more method as onPermissionResult, this method is used to check whether permission is granted or denied by the user.

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note − Make sure you are connected to your real device or emulator.

Output


Conclusion

In the above article we have taken a look on How to add runtime permission within our android application.

Updated on: 08-May-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements