Javascript required
Skip to content Skip to sidebar Skip to footer

Android What Happens When You Request Permission When the Permission Has Been Denied Dont Ask Again

Every Android app runs in a limited-access sandbox. If your app needs to use resource or information outside of its own sandbox, you lot tin can declare a permission and set a permission request that provides this access. These steps are part of the workflow for using permissions.

If you declare any unsafe permissions, and if your app is installed on a device that runs Android vi.0 (API level 23) or higher, you must asking the dangerous permissions at runtime by following the steps in this guide.

If you don't declare any dangerous permissions, or if your app is installed on a device that runs Android 5.1 (API level 22) or lower, the permissions are automatically granted, and you don't need to complete whatsoever of the remaining steps on this page.

Basic principles

The bones principles for requesting permissions at runtime are as follows:

  • Inquire for permissions in context, when the user starts to interact with the feature that requires information technology.
  • Don't block the user. Always provide the option to cancel an educational UI menstruation related to permissions.
  • If the user denies or revokes a permission that a feature needs, gracefully degrade your app so that the user can continue using your app, possibly by disabling the feature that requires the permission.
  • Don't assume whatever system beliefs. For example, don't assume that permissions appear in the aforementioned permission group. A permission grouping merely helps the arrangement minimize the number of system dialogs that are presented to the user when an app requests closely-related permissions.

Workflow for requesting permissions

Before you declare and request runtime permissions in your app, evaluate whether your app needs to do so. You can fulfill many apply cases in your app, such every bit taking photos, pausing media playback, and displaying relevant ads, without needing to declare any permissions.

If you conclude that your app needs to declare and request runtime permissions, consummate these steps:

  1. In your app'southward manifest file, declare the permissions that your app might need to request.
  2. Blueprint your app's UX and then that specific actions in your app are associated with specific runtime permissions. Users should know which deportment might require them to grant permission for your app to access individual user data.
  3. Await for the user to invoke the task or action in your app that requires access to specific private user information. At that fourth dimension, your app can request the runtime permission that'due south required for accessing that information.
  4. Check whether the user has already granted the runtime permission that your app requires. If and then, your app tin access the private user information. If not, continue to the next step.

    You must check whether you have that permission every time you lot perform an operation that requires that permission.

  5. Check whether your app should show a rationale to the user, explaining why your app needs the user to grant a detail runtime permission. If the organisation determines that your app shouldn't show a rationale, proceed to the next pace straight, without showing a UI element.

    If the system determines that your app should testify a rationale, withal, nowadays the rationale to the user in a UI chemical element. This rationale should clearly explain what data your app is trying to access, and what benefits the app can provide to the user if they grant the runtime permission. After the user acknowledges the rationale, continue to the next step.

  6. Asking the runtime permission that your app requires in guild to access the private user data. The system displays a runtime permission prompt, such as the one shown on the permissions overview page.

  7. Check the user's response, whether they chose to grant or deny the runtime permission.

  8. If the user granted the permission to your app, you can access the private user information. If the user denied the permission instead, gracefully degrade your app experience so that it provides functionality to the user, even without the information that'south protected past that permission.

Effigy one illustrates the workflow and set up of decisions associated with this process:

Effigy one. Diagram that shows the workflow for declaring and requesting runtime permissions on Android.

Determine whether your app was already granted the permission

To check if the user has already granted your app a detail permission, pass that permission into the ContextCompat.checkSelfPermission() method. This method returns either PERMISSION_GRANTED or PERMISSION_DENIED, depending on whether your app has the permission.

Explain why your app needs the permission

The permissions dialog shown past the system when y'all call requestPermissions() says what permission your app wants, only doesn't say why. In some cases, the user may find that puzzling. Information technology'due south a skillful idea to explain to the user why your app wants the permissions earlier you telephone call requestPermissions().

Research shows that users are much more comfortable with permissions requests if they know why the app needs them. A user study showed that:

...a user'due south willingness to grant a given permission to a given mobile app is strongly influenced past the purpose associated with such a permission. For instance a user's willingness to grant access to their location will vary based on whether the request is required to back up the app's core functionality or whether it is to share this data with an ad network or an analytics company. 1

Afterward collaborating with others on inquiry into this topic, Professor Jason Hong from CMU concluded that, in general:

...when people know why an app is using something as sensitive as their location — for example, for targeted advertising — it makes them more comfortable than when simply told an app is using their location. i

As a consequence, if you're merely using a fraction of the API calls that fall under a permission grouping, it helps to explicitly list which of those permissions you're using, and why. For example:

  • If y'all're merely using fibroid location, let the user know this in your app description or in help articles about your app.
  • If you need access to SMS messages to receive authentication codes that protect the user from fraud, let the user know this in your app description and when your app first needs to access the data.

    Note: If your app targets Android 8.0 (API level 26) or higher, don't request the READ_SMS permission as part of verifying a user'south credentials. Instead, generate an app-specific token using createAppSpecificSmsToken(), then pass this token to another app or service that tin send a verification SMS message.

Nether certain conditions, information technology'due south likewise advantageous to let users know about sensitive data accesses in real time. For example, if yous're accessing the camera or microphone, it'southward usually a good idea to let the user know with a notification icon somewhere in your app, or in the notification tray (if the application is running in the background), so it doesn't seem like you're collecting data surreptitiously.

Ultimately, if you lot demand to request a permission to make something in your app piece of work, just the reason is non clear to the user, find a fashion to let the user know why you lot need the nigh sensitive permissions.

If the ContextCompat.checkSelfPermission() method returns PERMISSION_DENIED, telephone call shouldShowRequestPermissionRationale(). If this method returns true, testify an educational UI to the user. In this UI, draw why the feature, which the user wants to enable, needs a particular permission.

Additionally, if your app requests a permission related to location, microphone, or camera, consider explaining why your app needs access to this information.

Asking permissions

Afterwards the user views an educational UI, or the return value of shouldShowRequestPermissionRationale() indicates that you don't need to show an educational UI this time, asking the permission. Users come across a system permission dialog, where they can cull whether to grant a particular permission to your app.

Traditionally, you manage a request code yourself as part of the permission asking and include this request code in your permission callback logic. Some other selection is to use the RequestPermission contract, included in an AndroidX library, where y'all let the arrangement to manage the permission request code for you. Because using the RequestPermission contract simplifies your logic, information technology's recommended that you use it when possible.

Let the system to manage the permission request code

To allow the arrangement to manage the request code that's associated with a permissions asking, add dependencies on the following libraries in your module's build.gradle file:

  • androidx.activeness, version 1.two.0 or later on.
  • androidx.fragment, version ane.3.0 or subsequently.

You can then use one of the post-obit classes:

  • To request a single permission, utilise RequestPermission.
  • To asking multiple permissions at the same time, use RequestMultiplePermissions.

The following steps evidence how to use the RequestPermission contract. The procedure is almost the same for the RequestMultiplePermissions contract.

  1. In your activity or fragment's initialization logic, laissez passer in an implementation of ActivityResultCallback into a call to registerForActivityResult(). The ActivityResultCallback defines how your app handles the user'south response to the permission request.

    Keep a reference to the return value of registerForActivityResult(), which is of type ActivityResultLauncher.

  2. To brandish the system permissions dialog when necessary, call the launch() method on the instance of ActivityResultLauncher that y'all saved in the previous footstep.

    After launch() is chosen, the system permissions dialog appears. When the user makes a selection, the system asynchronously invokes your implementation of ActivityResultCallback, which you defined in the previous step.

    Note: Your app cannot customize the dialog that appears when yous call launch(). To provide more information or context to the user, change your app'south UI so that it'south easier for users to empathize why a feature in your app needs a particular permission. For example, you might change the text in the push button that enables the feature.

    Also, the text in the organization permission dialog references the permission grouping associated with the permission that you requested. This permission grouping is designed for organization ease-of-apply, and your app shouldn't rely on permissions beingness within or exterior of a specific permission group.

The post-obit lawmaking snippet shows how to handle the permissions response:

Kotlin

// Register the permissions callback, which handles the user's response to the // system permissions dialog. Salvage the render value, an instance of // ActivityResultLauncher. You can use either a val, every bit shown in this snippet, // or a lateinit var in your onAttach() or onCreate() method. val requestPermissionLauncher =     registerForActivityResult(RequestPermission()     ) { isGranted: Boolean ->         if (isGranted) {             // Permission is granted. Proceed the action or workflow in your             // app.         } else {             // Explain to the user that the feature is unavailable because the             // features requires a permission that the user has denied. At the             // same time, respect the user's determination. Don't link to organisation             // settings in an effort to convince the user to change their             // decision.         }     }            

Coffee

// Register the permissions callback, which handles the user's response to the // system permissions dialog. Save the return value, an case of // ActivityResultLauncher, as an instance variable. private ActivityResultLauncher<String> requestPermissionLauncher =     registerForActivityResult(new RequestPermission(), isGranted -> {         if (isGranted) {             // Permission is granted. Continue the action or workflow in your             // app.         } else {             // Explain to the user that the feature is unavailable because the             // features requires a permission that the user has denied. At the             // same time, respect the user'due south decision. Don't link to system             // settings in an effort to convince the user to change their             // decision.         }     });            

And this lawmaking snippet demonstrates the recommended process of checking for a permission, and requesting a permission from the user when necessary:

Kotlin

when {     ContextCompat.checkSelfPermission(              CONTEXT,             Manifest.permission.REQUESTED_PERMISSION              ) == PackageManager.PERMISSION_GRANTED -> {         // Y'all can use the API that requires the permission.     }     shouldShowRequestPermissionRationale(...) -> {         // In an educational UI, explain to the user why your app requires this         // permission for a specific characteristic to behave as expected. In this UI,         // include a "abolish" or "no thank you" push that allows the user to         // keep using your app without granting the permission.         showInContextUI(...)     }     else -> {         // You can directly inquire for the permission.         // The registered ActivityResultCallback gets the result of this request.         requestPermissionLauncher.launch(                 Manifest.permission.REQUESTED_PERMISSION)     } }            

Java

if (ContextCompat.checkSelfPermission(              CONTEXT, Manifest.permission.REQUESTED_PERMISSION) ==         PackageManager.PERMISSION_GRANTED) {     // You can use the API that requires the permission.     performAction(...); } else if (shouldShowRequestPermissionRationale(...)) {     // In an educational UI, explicate to the user why your app requires this     // permission for a specific feature to acquit as expected. In this UI,     // include a "cancel" or "no cheers" button that allows the user to     // keep using your app without granting the permission.     showInContextUI(...); } else {     // You tin directly ask for the permission.     // The registered ActivityResultCallback gets the result of this request.     requestPermissionLauncher.launch(             Manifest.permission.REQUESTED_PERMISSION); }            

Manage the permission request lawmaking yourself

Equally an culling to allowing the system to manage the permission request lawmaking, you can manage the permission request code yourself. To do and so, include the request lawmaking in a call to requestPermissions().

The following lawmaking snippet demonstrates how to request a permission using a asking code:

Kotlin

when {     ContextCompat.checkSelfPermission(              CONTEXT,             Manifest.permission.REQUESTED_PERMISSION              ) == PackageManager.PERMISSION_GRANTED -> {         // You tin can use the API that requires the permission.         performAction(...)     }     shouldShowRequestPermissionRationale(...) -> {         // In an educational UI, explicate to the user why your app requires this         // permission for a specific feature to behave as expected. In this UI,         // include a "cancel" or "no thank you" push that allows the user to         // go on using your app without granting the permission.         showInContextUI(...)     }     else -> {         // You can directly ask for the permission.         requestPermissions(CONTEXT,                 arrayOf(Manifest.permission.REQUESTED_PERMISSION),              REQUEST_CODE)     } }            

Java

if (ContextCompat.checkSelfPermission(              CONTEXT, Manifest.permission.REQUESTED_PERMISSION) ==         PackageManager.PERMISSION_GRANTED) {     // You can use the API that requires the permission.     performAction(...); } else if (shouldShowRequestPermissionRationale(...)) {     // In an educational UI, explain to the user why your app requires this     // permission for a specific feature to comport equally expected. In this UI,     // include a "cancel" or "no thanks" push button that allows the user to     // keep using your app without granting the permission.     showInContextUI(...); } else {     // You lot can straight enquire for the permission.     requestPermissions(CONTEXT,             new String[] { Manifest.permission.REQUESTED_PERMISSION              },              REQUEST_CODE); }            

Subsequently the user responds to the organization permissions dialog, the system then invokes your app's implementation of onRequestPermissionsResult(). The system passes in the user response to the permission dialog, as well equally the request code that yous defined, as shown in the following lawmaking snippet:

Kotlin

override fun onRequestPermissionsResult(requestCode: Int,         permissions: Array<String>, grantResults: IntArray) {     when (requestCode) {              PERMISSION_REQUEST_CODE              -> {             // If request is cancelled, the result arrays are empty.             if ((grantResults.isNotEmpty() &&                     grantResults[0] == PackageManager.PERMISSION_GRANTED)) {                 // Permission is granted. Continue the action or workflow                 // in your app.             } else {                 // Explicate to the user that the feature is unavailable considering                 // the features requires a permission that the user has denied.                 // At the same time, respect the user's decision. Don't link to                 // system settings in an effort to convince the user to change                 // their determination.             }             return         }          // Add other 'when' lines to bank check for other         // permissions this app might request.         else -> {             // Ignore all other requests.         }     } }

Java

@Override public void onRequestPermissionsResult(int requestCode, String[] permissions,         int[] grantResults) {     switch (requestCode) {         case              PERMISSION_REQUEST_CODE:             // If asking is cancelled, the result arrays are empty.             if (grantResults.length > 0 &&                     grantResults[0] == PackageManager.PERMISSION_GRANTED) {                 // Permission is granted. Continue the action or workflow                 // in your app.             }  else {                 // Explain to the user that the feature is unavailable considering                 // the features requires a permission that the user has denied.                 // At the same fourth dimension, respect the user's decision. Don't link to                 // organisation settings in an effort to convince the user to change                 // their decision.             }             return;         }         // Other 'case' lines to check for other         // permissions this app might request.     } }

Requesting multiple permissions

When you asking location permissions, follow the same best practices every bit you would for any other runtime permission. One important difference when information technology comes to location permissions is that the arrangement includes multiple permissions related to location. Which permissions you asking, and how you lot request them, depend on the location requirements for your app'due south employ example.

Foreground location

If your app contains a characteristic that shares or receives location information but once, or for a defined corporeality of time, then that feature requires foreground location access. Some examples include the post-obit:

  • Within a navigation app, a feature allows users to get turn-by-turn directions.
  • Within a messaging app, a characteristic allows users to share their current location with another user.

The arrangement considers your app to be using foreground location if a feature of your app accesses the device's current location in 1 of the following situations:

  • An activity that belongs to your app is visible.
  • Your app is running a foreground service. When a foreground service is running, the arrangement raises user awareness by showing a persistent notification. Your app retains access when it'south placed in the background, such as when the user presses the Domicile button on their device or turns their device'due south display off.

    Additionally, it'south recommended that you declare a foreground service type of location, as shown in the post-obit lawmaking snippet. On Android x (API level 29) and higher, you lot must declare this foreground service type.

    <!-- Recommended for Android 9 (API level 28) and lower. --> <!-- Required for Android ten (API level 29) and higher. --> <service     android:name="MyNavigationService"              android:foregroundServiceType="location"              ... >     <!-- Whatever inner elements would go here. --> </service>            

You declare a need for foreground location when your app requests either the ACCESS_COARSE_LOCATION permission or the ACCESS_FINE_LOCATION permission, as shown in the following snippet:

<manifest ... >   <!-- Ever include this permission -->   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />    <!-- Include only if your app benefits from precise location access. -->   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> </manifest>        

Groundwork location

An app requires background location admission if a feature within the app constantly shares location with other users or uses the Geofencing API. Several examples include the following:

  • Within a family location sharing app, a characteristic allows users to continuously share location with family members.
  • Within an IoT app, a feature allows users to configure their dwelling devices such that they turn off when the user leaves their dwelling house and plow back on when the user returns home.

The organization considers your app to exist using background location if it accesses the device's current location in any situation other than the ones described in the foreground location department. The background location precision is the same equally the foreground location precision, which depends on the location permissions that your app declares.

On Android 10 (API level 29) and higher, you must declare the ACCESS_BACKGROUND_LOCATION permission in your app's manifest in society to request background location access at runtime. On earlier versions of Android, when your app receives foreground location admission, it automatically receives groundwork location admission every bit well.

<manifest ... >   <!-- Required only when requesting background location access on        Android 10 (API level 29) and higher. -->   <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /> </manifest>        

Handle permission denial

If the user denies a permission asking, your app should assist users sympathise the implications of denying the permission. In particular, your app should make users enlightened of the features that don't work because of the missing permission. When y'all do so, keep the following best practices in mind:

  • Guide the user'due south attention. Highlight a specific office of your app's UI where there'due south express functionality because your app doesn't have the necessary permission. Several examples of what you could practise include the post-obit:

    • Show a message where the feature'due south results or data would have appeared.
    • Display a dissimilar button that contains an error icon and color.
  • Be specific. Don't display a generic message; instead, mention which features are unavailable because your app doesn't have the necessary permission.

  • Don't cake the user interface. In other words, don't display a total-screen warning message that prevents users from standing to use your app at all.

Tip: Your app should encourage the all-time user feel possible, even afterwards permission denials. For example, if microphone access is denied, you should still promote full usability of text functionality.

At the aforementioned time, your app should respect the user's conclusion to deny a permission. Starting in Android 11 (API level 30), if the user taps Deny for a specific permission more than than one time during your app's lifetime of installation on a device, the user doesn't see the system permissions dialog if your app requests that permission again. The user's action implies "don't ask once more." On previous versions, users would see the system permissions dialog each fourth dimension your app requested a permission, unless the user had previously selected a "don't ask over again" checkbox or choice.

If a user denies a permission request more than than in one case, this is considered a permanant denial. It's very important to only prompt users for permissions when they need access to a specific feature, otherwise you may inadvertently lose the ability to re-request permissions.

In sure situations, the permission might be denied automatically, without the user taking whatever activeness. (Similarly, a permission might be granted automatically every bit well.) It's of import to non presume anything about automatic behavior. Each time your app needs to access functionality that requires a permission, you should check that your app is still granted that permission.

To provide the all-time user experience when asking for app permissions, also see App permissions all-time practices.

One-fourth dimension permissions

The option called 'Only this time' is the second of three buttons in      the dialog.
Effigy 2. System dialog that appears when an app requests a one-time permission.

Starting in Android 11 (API level thirty), whenever your app requests a permission related to location, microphone, or camera, the user-facing permissions dialog contains an selection chosen Just this time, every bit shown in Figure 2. If the user selects this pick in the dialog, your app is granted a temporary one-time permission.

Your app tin can then access the related information for a period of time that depends on your app'due south behavior and the user's deportment:

  • While your app'due south activity is visible, your app tin can admission the data.
  • If the user sends your app to the background, your app can continue to admission the data for a curt period of fourth dimension.
  • If you launch a foreground service while the action is visible, and the user then moves your app to the groundwork, your app tin can keep to access the data until that foreground service stops.
  • If the user revokes the 1-fourth dimension permission, such as in system settings, your app cannot access the data, regardless of whether yous launched a foreground service. Every bit with any permission, if the user revokes your app's one-time permission, your app's procedure terminates.

When the user adjacent opens your app and a feature in your app requests access to location, microphone, or camera, the user is prompted for the permission once again.

Android auto-resets permissions of unused apps

If your app targets Android xi (API level 30) or higher and isn't used for a few months, the organization protects user data by automatically resetting the sensitive runtime permissions that the user had granted your app. Acquire more than in the guide virtually app hibernation.

Request to become the default handler if necessary

Some apps depend on access to sensitive user information related to call logs and SMS messages. If y'all want to request the permissions specific to call logs and SMS messages and publish your app to the Play Store, you lot must prompt the user to gear up your app every bit the default handler for a core arrangement role earlier requesting these runtime permissions.

For more than information on default handlers, including guidance on showing a default handler prompt to users, run across the guide on permissions used simply in default handlers.

Grant all runtime permissions for testing purposes

To grant all runtime permissions automatically when you install an app on an emulator or test device, use the -g pick for the adb shell install command, every bit demonstrated in the post-obit code snippet:

adb crush install          -g          PATH_TO_APK_FILE        

Additional resources

For boosted data about permissions, read these manufactures:

  • Permissions overview
  • App permissions best practices

To learn more almost requesting permissions, download the post-obit sample apps:

  • Android RuntimePermissionsBasic Sample Java | Kotlin

Android What Happens When You Request Permission When the Permission Has Been Denied Dont Ask Again

Source: https://developer.android.com/training/permissions/requesting