Android 6.0 App permissions (ii)--Work with system permissions (working with systems Permissions) use Markdown to rearrange the layout

Source: Internet
Author: User

To protect system integration and user privacy, Android runs each program in a restricted-access sandbox. If the app wants to use other resources or information outside of its sandbox, it must explicitly request permissions. Depending on the type of permission the application requests, the system may automatically authorize or authorize by asking the user

This section shows you how to declare and grant permissions for your app.

Declare Permissions (Claim permission)

Each Android app runs in a restricted-access sandbox. If the app wants to use other resources or information outside of its sandbox, it needs to request the correct permissions. You can declare the permissions that your app needs by listing these permissions in app manifest.

Depending on the sensitivity of the permission, the system may automatically authorize, or the user of the device may want to license the permission request. For example, if your app asks for permission to turn off the device's flash, the system will automatically give it this permission, but if your app needs to read the user's contacts, you'll be asked to allow that permission. Depending on the platform version that is not used, the user does not authorize either: when the installation is authorized (Android 5.1 or lower) or when the app is running (Android 6.0 or higher)

Decide what permissions you need

When you develop your app, you should be aware that your app is using some functionality that requires permissions. The typical scenario is that whenever an application is going to use information or resources that are not created by itself or perform actions that affect the behavior of a device or other application, it will require permissions. For example, if your app needs to access the network, use the device's camera, or turn WiFi on or off, it needs the right permissions. To view a list of system permissions, you can view it (Normal anddangerous Permissions section)

Your app just needs the permissions of the actions it will perform directly. If your app asks other apps to perform tasks or provide data, it doesn't require permissions. For example, if your app needs to read this user's address book, the app requires Read_contacts permissions. But if your app uses a intent to request information from a user's Contacts app, your app doesn't need any permissions. However, the Contacts application must have the appropriate permissions. For more information, see the consider Using an Intent section.

Add permissions to the app manifest (add Permissions to the Manifest)

To declare those based on permissions, put the element in your app manifest, as the child element of the top layer. For example, an app that needs to send an SMS message requires the following code to declare permissions.

<manifestxmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.snazzyapp">    <uses-permissionandroid:name="android.permission.SEND_SMS"/>    <application ...>        ...    </application></manifest>

After you declare a permission, the behavior of the system depends on how sensitive the permissions are. If this permission does not affect the user's privacy, the system will automatically authorize. If this permission may allow access to sensitive user information, the system will ask the user to approve the request.

Requesting Permissions at Run time

Starting with Android 6.0 (API level 23), users are authorized when the app is running, not when the app is installed. This method (approach) simplifies (streamline) the application installation process, because users do not need to be authorized when they install or update the application. At the same time, it gives the user more control over the application function; For example, a user can choose to have a camera app access the camera, but not allow it to access the device's location. Users can revoke (REVOKE) These permissions at any time through the app's settings interface.

System Permissions is divided into two categories, normal and dangerous (normal and dangerous):

    • Normal Permissions does not directly bear the risk of user privacy. If your app is listed in its manifest
      A normal permission, the system will automatically authorize it.
    • Dangerous permissions will allow the app to access the user's private (confidential) data. If your app lists a normal permission in its manifest, the system automatically authorizes it. If you are listing a dangerous permission, the user must explicitly authorize your app.

In all Android versions, as declaring permissions describes, your app needs to declare both the normal and dangerous permissions it needs in the app's manifest. However, the specific effect of that statement will vary depending on the version of the system and the target SDK level (targetsdkversion) of your app.

    • If the device is running on Android 5.1 or earlier, or your app target SDK is 22 or lower,
      If you list a dangerous privilege in your app manifest, the user must authorize it when they install the app, and if they don't have it, the system won't install it at all.
    • If your device is running on Android 6.0 (API level
      23) or later, your app must list the required permissions in manifest, and it must request each of the dangerous permissions it needs when the app is running. The user can authorize or deny each permission, and the app can continue to run with limited functionality even if the user denies the requested permission.

Note: Starting with Android 6.0, users can revoke the app's permissions at any time, even if the app's TARGETAPI level is lower. You should test your app to verify that it works properly without the required permissions, regardless of which API-level app your app points to.

This section describes how to use the Android support Library to check and request permissions. The Android Framework provides a similar approach on Android 6.0. However, it's easier to use the support library because your app doesn't need to check the Android version it's in before calling this method

Check for Permissions

If your app requires a dangerous permission, you must check to see if your app already has that permission every time you perform an action that requires that permission. Users can often easily revoke permissions that have been given, so even if the app used the camera permissions yesterday, it can't be assumed that it still has this right today.

To check if you have a permission, call the Contextcompat.checkselfpermission () method. For example, the following fragment (Snippet) shows us how to check whether an activity has permission to write a calendar.

// Assume thisActivity is the current activity
int permission Check=ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.WRITE_CALENDAR);

If the application has the above permissions, this method returns packagemanager.permission_granted, and the application can perform the appropriate operation. If the app does not have this permission, this method returns Permission_denied, and the app must explicitly request permissions from the user.

Request Permissions (Requesting permission)

If your app needs a dangerous permission listed in your app manifest, you must ask the user to authorize the permission. Android provides several ways you can apply for a permission. Calling these methods will pop up a standard android dialog box that you can't customize.

Explain Why the app needs permissions

In some environments (circumstance), you might want to help users understand why your app needs a permission, for example, if a user launches a picture app, the user might not be surprised that the app requires permission to use the camera, But the user may not understand why the app wants to access the user's location or contact person. Before you ask for a permission, you should consider giving the user an explanation. If you provide too much explanation, the user may find the application annoying and remove it.

You may use a way to provide an explanation only if the user has rejected a permission request. If the user has been trying to use the function that requires permission, but has refused the permission request, it may indicate that the user does not understand why the application needs this permission when using this feature. In that scenario, it might be a good idea to display an explanation of the content to the user.

To help find scenarios where users might need an explanation, Android provides a tool approach. Shouldshowrequestpermissionrationale (). This method returns true if the permission has been requested by the application before the user rejects it.

Note: If a user denies a permission request in the past and chooses the "Don't ask again" option, this method will return false and this method will return FALSE if the device policy prohibits the app from having that permission.

Request the permissionsyou need.

If your app does not already have the permissions it needs, the app must call a Requestpermissions () method to request the appropriate permissions. Your app passes the permissions it wants and the request code of an integer that you define for this permission request. This method runs asynchronously (asynchronously): it returns immediately, and after the user responds to the dialog, the system callbacks the application's callback function and passes the result and the same application over to Requestpermissions (). Request Code comes back.

The following code checks to see if the app has permission to read contacts and, if necessary, requests those permissions.

//Here, thisactivity are the current activityif (contextcompat.  Checkselfpermission (thisactivity, Manifest.permission.READ_CONTACTS) !=packagemanager.permissio n_granted){//Should we show an explanation?    if (activitycompat.  Shouldshowrequestpermissionrationale (thisactivity, Manifest.permission.READ_CONTACTS)){//Show an expanation to the user *asynchronously*--don ' t block        //This thread waiting for the user ' s response! After Theuser        //sees the explanation, try again to request thepermission.}else{//No explanation needed, we can request the permission.Activitycompat. Requestpermissions(Thisactivity, NewString[]{Manifest. Permission. Read_contacts}, My_permissions_request_read_contacts);//My_permissions_request_read_contacts is an        //app-defined int constant. The callback method gets the        //result of the request.}}

Note: When your app calls Requestpermissions (), the system displays a standard dialog box to the user, your app cannot modify the dialog, and if you need to provide any information or explain the content to the user, you apply the call to Requestpermissions () Do that before. As described above.
Handle the answer to a permission request (Handle the permissions request response)

When your app requests permissions, the system presents a dialog to the user. When the user responds, the system calls your app's Onrequestpermissionsresult () method, passing the user's response to it. Your user must reload this method to see if the required permissions are granted. The system will pass the same request code you passed to Requestpermissions () to the callback function. For example, if an app requests read_contacts access, it might have the following callback methods:

@Override Public void Onrequestpermissionsresult(intRequestcode, String permissions[],int[] grantresults) {Switch(Requestcode) { Casemy_permissions_request_read_contacts:{//If request iscancelled, the result arrays is empty.            if(grantresults.length>0&& grantresults[0]==packagemanager.permission_granted) {//Permission wasgranted, yay! do the                //Contacts-relatedtask You need to do.}Else{//Permission Denied,boo! Disable the                //Functionality thatdepends on this permission.}return; }//Other ' case ' lines to check for other        //Permissions This app might request}}

The dialog box displayed by this system describes the permission groups your app needs to access, and it does not list a specific permission. For example, if you request Read_contacts permissions, the System dialog box will only say that your app needs to access the device's contacts. Users only need to authorize each permission group once. If your app requests any of the other permissions in that permission group (the permissions you have listed in your app manifest), the system automatically authorizes that permission. When you request this permission, the system invokes the application's Onrequestpermissionsresult () callback method and passes the permission_granted.

Tip: Your app still needs to explicitly request every permission it needs, even if the user has authorized another permission in the same permission group. Also, the partitioned permission groups may change in future Android release. Your code should rely on specific assumptions that are or are not in the same permission group.

For example, suppose you list the read_contacts and write_contacts two permissions in your app manifest, if you request read_contacts, the user grants this permission, and then you request Write_contacts, The system grants you this permission without interacting with the user.

If the user rejects your permission request, your app needs to take the right action. For example, your app might need to display a dialog box explaining why it cannot perform the action requested by the user that requires that permission.

When the system asks the user to grant a permission, the user can see an option, which will tell the system not to ask for permission the next time. If this permission is checked, when the app uses Requestpermissions () again to request permission, the system will deny the user directly without asking. The system invokes the application's Onrequestpermissionsresult () callback method and passes the permission_denied to it. The exact form is the same as when the user clicks on the permission request. This means that when you call Requestpermissions (), you cannot assume that any form of direct interaction with the user is occurring.

Permissions Best Practice

It is easy for an application to strike a user through a permission request. If users find that an app is annoying, or if the user is worried about what the app will do with their information, they may simply stop using the app or simply delete it. The following best practices can help avoid these bad user experiences.

Consider Using an Intent

In many cases, you have two options for performing a task in your application. You can ask your app to request permissions to perform the corresponding action. Of course, you can also choose to have your app use intent for other apps to perform this task.

For example, let's say your app needs to take pictures with the device's camera, your app can request camera permissions (allowing your app to access the camera directly), and your app will use the Camer API to control the camera and take pictures. This method gives your app complete control over the photo process and lets you incorporate the camera UI into your app.

However, if you do not need this complete control, you can use a action_image_capture intent to request a photo. When you send this intent, the user is prompted to select a camera app (if there is no default camera app). The user uses the selected camera to take a photo, and the app returns the resulting photo to your app's Onactivityresult () method.

Similarly, if you need to make a phone call, access the user's contacts, and so on, you can do these things by creating a suitable intent. Or you can request the corresponding permission to access the appropriate object directly. Each approach has its advantages and disadvantages:

If you use permissions:
    • When you perform an operation, your app has complete control over the user experience. However, this broad control increases the complexity of your task because you need to design a suitable UI.
    • The user is prompted for a permission request, whether at run time or during installation (depending on the user's Android version). Your app can then perform operations without the need to generate additional interaction with the user. However, if the user does not give these permissions (or is subsequently canceled), your app will no longer be able to perform these actions.
If you use intent:
    • You do not need to design the UI for this operation. Those applications that deal with intent provide the UI. However, this means that you cannot control all user experiences. Users may interact with a UI that you have never seen before.
    • If the user does not have a default app, the user is prompted to select an app. If the user does not specify a default processor, they will generate an additional dialog box each time the action is performed.
Only Ask for Permissions you need

Every time you ask for a permission, you are forcing the user to make a decision. Your app makes you make these requests as small as possible. If the user is on Android 6.0 or higher, each time the user tries to use some new app features that require permission, the app must use a permission request to interrupt the user's work. If the user is running on an earlier version, the user must be authorized when the app is installed. If the list is too long or inaccurate, the user may decide not to install your app. For these reasons, you should try to minimize the permissions your application needs.

Usually your app can avoid applying permissions by using intent. If a feature is not a core part of your app's functionality, you should consider using other programs to handle the task.

Do not overwhelm the User

If the user device is running on Android 6.0 or later, the user must authorize your app when they use the app. Once you have the user facing a lot of permission requests, you can hit the confidence that they are using the app and make them uninstall the app. Cameras, you should only authorize them when you need them.

In some cases, one or more permissions may be necessary for your app. It may make sense to request all of these permissions when the app is started. For example, if you write a picture app, the app will need to access the device's camera, and when the user launches the app for the first time, they won't be surprised by the operation requesting camera permissions. However, if the same app also has the need to share pictures through the user's contacts, you may not be asked to request Read_contacts permissions when you first log in. Instead, you should wait until the user tries to use the share feature and asks for permission to pop up the reminder.

If your app provides an app using tutorials, it's meaningful to request the app's required permissions at the end of the tutorial.

Explain why need Permissions

When you call Requestpermissions () The Permissions dialog box displayed by the system tells us what permissions your app wants, but it doesn't say why, in some cases, the user may find this confusing point. It is a good idea to explain to the user before calling Requestpermissions () Why your app wants these permissions.

For example, a picture app might want to use location services so that it can place information on a picture. A typical user may not understand why a picture should include location information, and will be confused about why a picture application wants to know the location information. So in this case, it's a good idea to tell the user this feature before calling Requestpermissions ().

One way to inform users is to combine these requests into an app tutorial that shows the features of the app in order, and explains what permissions they need to show, for example, a picture app tutorial that shows the feature of "share pictures with your contacts." Then, you can tell the user that they need permission to view the user's contacts for the app. Then, the app can call Requestpermissions () to request permission from the user, and of course, not every user will follow the tutorial, so you still need to check and request permissions in the user's normal operation.

Test for Both Permissions Models

Starting with Android 6.0, users can authorize or revoke permissions while the app is running, rather than checking the app's installation as it did before. Therefore, you must test your application under a broader range of conditions. Before Android6.0, you can reasonably assume that your application runs with permissions declared in all of its application manifests. But according to the new permission model, you can no longer make such assumptions. The following recommendations will help identify code issues related to permissions on devices running on API Leve 23 or higher:

    • Identify your app's current permissions and associated code paths
    • Testing a user-protected service or data across rights
    • Test multiple authorized and non-authoritative combinations of permissions. For example, a camera app might list camera, read_contacts, and access_fine_location in manifest. You should use each of these permissions to test the app, turn on one or more of the permissions in the shutdown, and make sure that the app can handle all permissions configuration. Remember, starting with Android6.0, users can turn off any app's permissions, even if that app's target apilevel is 22 or lower.
    • Use the ADB tool to manage permissions from the command line:
...
    • Applications that are analyzed for services that use permissions

Android 6.0 App permissions (ii)--Work with system permissions (working with systems Permissions) use Markdown to rearrange the layout

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.