Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Request Permissions in Android Application?
Next article icon

How to Request Permissions in Android Application?

Last Updated : 09 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Starting from Android 6.0 (API 23), users are not asked for permissions at the time of installation rather developers need to request the permissions at the run time. Only the permissions that are defined in the manifest file can be requested at run time.

Types of Permissions

1. Install-Time Permissions: If the Android 5.1.1 (API 22) or lower, the permission is requested at the installation time at the Google Play Store.

If the user Accepts the permissions, the app is installed. Else the app installation is canceled.

2. Run-Time Permissions: If the Android 6 (API 23) or higher, the permission is requested at the run time during the running of the app.

If the user Accepts the permissions, then that feature of the app can be used. Else to use the feature, the app requests permission again.

So, now the permissions are requested at runtime. In this article, we will discuss how to request permissions in an Android Application at run time. 


Steps for Requesting permissions at run time  

Step 1: Declare the permission in the Android Manifest file

In Android, permissions are declared in the AndroidManifest.xml file using the uses-permission tag. 

<uses-permission android:name=”android.permission.PERMISSION_NAME”/>

Here we are declaring storage and camera permission.

XML
<uses-feature     android:name="android.hardware.camera"     android:required="false" />  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 


Step 2: Modify activity_main.xml file

Add a button to request permission on button click. Permission will be checked and requested on button click. Open the activity_main.xml file and add two buttons to it.

activity_main.xml:

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:gravity="center"     tools:context=".MainActivity">      <Button         android:id="@+id/button"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Request Permissions"/>  </LinearLayout> 


Step 3: Working with MainActivity file

Check whether permission is already granted or not. If permission isn't already granted, request the user for the permission: In order to use any service or feature, the permissions are required. Hence we have to ensure that the permissions are given for that. If not, then the permissions are requested.

  • Check for permissions: Beginning with Android 6.0 (API level 23), the user has the right to revoke permissions from any app at any time, even if the app targets a lower API level. So to use the service, the app needs to check for permissions every time.
  • Request Permissions: When PERMISSION_DENIED is returned from the checkSelfPermission() method in the above syntax, we need to prompt the user for that permission. Android provides several methods that can be used to request permission, such as requestPermissions().
  • Override onRequestPermissionsResult() method: onRequestPermissionsResult() is called when user grant or decline the permission. RequestCode is one of the parameters of this function which is used to check user action for the corresponding requests. Here a toast message is shown indicating the permission and user action. 
MainActivity.java
package org.geeksforgeeks.demo;  import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.widget.Button; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import java.util.ArrayList; import java.util.List;  public class MainActivity extends AppCompatActivity {      // Unique request code for permission request     private static final int PERMISSION_REQUEST_CODE = 123;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          // Find the button in the layout and set a click listener         Button button = findViewById(R.id.button);         button.setOnClickListener(v -> requestPermissions());     }      // Function to check and request necessary permissions     private void requestPermissions() {                  // List of permissions the app may need         String[] permissions = {             Manifest.permission.ACCESS_COARSE_LOCATION,             Manifest.permission.ACCESS_FINE_LOCATION,             Manifest.permission.CAMERA,             Manifest.permission.READ_EXTERNAL_STORAGE,             Manifest.permission.WRITE_EXTERNAL_STORAGE         };          List<String> permissionsToRequest = new ArrayList<>();          // Filter out the permissions that are not yet granted         for (String permission : permissions) {             if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {                 permissionsToRequest.add(permission);             }         }          // If there are permissions that need to         // be requested, ask the user for them         if (!permissionsToRequest.isEmpty()) {             ActivityCompat.requestPermissions(                 this,                 permissionsToRequest.toArray(new String[0]), // Convert list to array                 PERMISSION_REQUEST_CODE // Pass the request code             );         } else {             // All permissions are already granted             Toast.makeText(this, "All permissions already granted", Toast.LENGTH_SHORT).show();         }     }      // Callback function that handles the     // result of the permission request     @Override     public void onRequestPermissionsResult(int requestCode,                                            @NonNull String[] permissions,                                            @NonNull int[] grantResults) {         super.onRequestPermissionsResult(requestCode, permissions, grantResults);          if (requestCode == PERMISSION_REQUEST_CODE) {             List<String> deniedPermissions = new ArrayList<>();              // Check which permissions were denied             for (int i = 0; i < permissions.length; i++) {                 if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {                     deniedPermissions.add(permissions[i]);                 }             }              if (deniedPermissions.isEmpty()) {                                  // All permissions granted                 Toast.makeText(this, "All permissions granted", Toast.LENGTH_SHORT).show();             } else {                                  // Some permissions were denied, show them in a Toast                 Toast.makeText(this, "Permissions denied: " + deniedPermissions, Toast.LENGTH_LONG).show();             }         }     } } 
MainActivity.kt
package org.geeksforgeeks.demo  import android.os.Bundle import android.widget.Button import androidx.appcompat.app.AppCompatActivity import android.Manifest import android.content.pm.PackageManager import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat  class MainActivity : AppCompatActivity() {      companion object {              // Unique request code for permission request         private const val PERMISSION_REQUEST_CODE = 123     }      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)           // Find the button in the layout and set a click listener         val button = findViewById<Button>(R.id.button)         button.setOnClickListener {                      // Call the function to request permissions             // when the button is clicked             requestPermissions()          }     }      // Function to check and request necessary permissions     private fun requestPermissions() {              // List of permissions the app may need         val permissions = arrayOf(             Manifest.permission.ACCESS_COARSE_LOCATION,             Manifest.permission.ACCESS_FINE_LOCATION,             Manifest.permission.CAMERA,             Manifest.permission.READ_EXTERNAL_STORAGE,             Manifest.permission.WRITE_EXTERNAL_STORAGE         )          // Filter out the permissions that are not yet granted         val permissionsToRequest = permissions.filter { permission ->             ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED         }          // If there are permissions that need to be requested, ask the user for them         if (permissionsToRequest.isNotEmpty()) {             ActivityCompat.requestPermissions(                 this,                 permissionsToRequest.toTypedArray(), // Convert list to array                 PERMISSION_REQUEST_CODE // Pass the request code             )         } else {             // All permissions are already granted             Toast.makeText(this, "All permissions already granted", Toast.LENGTH_SHORT).show()         }     }      // Callback function that handles the result of the permission request     override fun onRequestPermissionsResult(         requestCode: Int,         permissions: Array<out String>,         grantResults: IntArray     ) {         super.onRequestPermissionsResult(requestCode, permissions, grantResults)          if (requestCode == PERMISSION_REQUEST_CODE) {                      // Combine permissions with their corresponding grant results             val deniedPermissions = permissions.zip(grantResults.toTypedArray())                 .filter { it.second != PackageManager.PERMISSION_GRANTED } // Filter out the denied ones                 .map { it.first } // Get the permission names              if (deniedPermissions.isEmpty()) {                 // All permissions granted                 Toast.makeText(this, "All permissions granted", Toast.LENGTH_SHORT).show()             } else {                 // Some permissions were denied, show them in a Toast                 Toast.makeText(this, "Permissions denied: $deniedPermissions", Toast.LENGTH_LONG).show()             }         }     } } 


Output:



Next Article
How to Request Permissions in Android Application?

A

aman neekhara
Improve
Article Tags :
  • Misc
  • Java
  • Android
  • Java-Android
Practice Tags :
  • Java
  • Misc

Similar Reads

    How to Add Manifest Permission to an Android Application?
    An AndroidManifest.xml file must be present in the root directory of every app project's source set. The manifest file provides crucial information about your app to Google Play, the Android operating system, and the Android build tools. Adding permissions to the file is equally important. In this a
    2 min read
    How to Build a SOS Mobile Application in Android Studio?
    The SOS applications are basically advanced emergency apps that can rescue you and/or your loved ones if you and/or they find themselves in a life-threatening emergency situation and need immediate assistance. When you need some personal assistance, you can actually turn on your phone and can call o
    15+ min read
    How to Build an Application to Test Motion Sensors in Android?
    In this article, we will be building a Motion Sensor Testing App Project using Java and XML in Android. The application will be using the hardware of the device to detect the movements. The components required to detect the motion are Accelerometer and Gyroscope. The Accelerometer is an electronic s
    6 min read
    Components of an Android Application
    There are some necessary building blocks that an Android application consists of. These loosely coupled components are bound by the application manifest file which contains the description of each component and how they interact. The manifest file also contains the app’s metadata, its hardware confi
    3 min read
    How to Enable Notification Runtime Permission in Android 13?
    Android 13 starts a new realm of new app permissions which are focussed on users' privacy and peace of mind, one of which is the permission to send notifications to the user. Notifications are an integral part of the Android Operating System, but when you have tons of apps installed, then receiving
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences