Android 6.0 Runtime permissions analysis and Best practices

Source: Internet
Author: User

1. Preface

Starting with Android 6.0 (API 23), the system permissions have changed a lot. Before the user installs the app, just list the permissions that the app needs to let the user know that they can be accessed after the app is installed. Starting with 6.0, some sensitive permissions need to be applied dynamically at the time of use, and the user can choose to deny access to these permissions, granted permissions, and users can go to the app Settings page to turn off authorization. This improves security for users, and can prevent some applications from malicious access to user data, but for development, it also adds a lot of work, this block does not do the matching processing, the app will be easy to crash when access.

2. Permission levels and permission groups

Permissions are mainly divided into normal, dangerous, signature and Signatureorsystem four levels, under normal circumstances we only need to understand the first two, that is, normal permissions and dangerous permissions.

2.1. Normal permissions

Normal permissions cover areas where the app needs to access its sandbox external data or resources, but is less risky for user privacy or other application operations. The app declares that it requires normal permissions, and the permission is automatically granted to the system. For example, if you set the time zone, the system grants this permission directly to the app, as long as the claim is applied. Below is the normal permission to API 23 (requires a wall-over access)

Normal Permissions Normal Permissions
Access_location_extra_commands Access_network_state
Access_notification_policy Access_wifi_state
BLUETOOTH Bluetooth_admin
Broadcast_sticky Change_network_state
Change_wifi_multicast_state Change_wifi_state
Disable_keyguard Expand_status_bar
Get_package_size Install_shortcut
INTERNET Kill_background_processes
Modify_audio_settings Nfc
Read_sync_settings Read_sync_stats
receive_boot_completed Reorder_tasks
Request_ignore_battery_optimizations Request_install_packages
Set_alarm Set_time_zone
Set_wallpaper Set_wallpaper_hints
Transmit_ir Uninstall_shortcut
Use_fingerprint Vibrate
Wake_lock Write_sync_settings
2.2. Dangerous rights

Dangerous permissions cover the areas where the application needs data or resources that involve user privacy information, or that may affect the operations of the user's stored data or other applications. For example, to read a user contact, in more than 6.0 of the system, you need to explicitly request permission at run time for the user.

2.3. Permission Groups

The system defines a permission group according to the purpose of the permission, each of which can belong to a permission group, each permission group can contain multiple permissions. For example, a contact permission group that includes reading contacts, modifying contacts, and getting account three permissions.
* If the app requests access to a dangerous permission, and the app does not currently have any permissions within the corresponding permission group, the system will pop-up to prompt the user to access the permission group (note that it is not a permission). For example, whether you're applying for read_contacts or write_contacts, it's a hint that the app needs access to the contact information.
* If a user requests access to a dangerous permission, and the application has granted additional permissions to the permission group, the system is directly authorized and no longer interacts with the user. For example, when an app has requested and granted Read_contacts permissions, the permission is granted immediately when the app requests write_contacts. The following are dangerous permissions and permission groups:

Permission Groups Permissions
CALENDAR Read_calendar
Write_calendar
CAMERA CAMERA
CONTACTS Read_contacts
Write_contacts
Get_accounts
Location Access_fine_location
Access_coarse_location
Microphone Record_audio
PHONE Read_phone_state
Call_phone
Read_call_log
Write_call_log
Add_voicemail
Use_sip
Process_outgoing_calls
Sensors Body_sensors
Sms Send_sms
Receive_sms
Read_sms
Receive_wap_push
Receive_mms
STORAGE Read_external_storage
Write_external_storage
3. Request permission at runtime

About the operation of the request permission, the official website is very clear, there are many other articles introduced, here is simply a list.

3.1. Check Permissions

Each time the application requires a dangerous permission, you need to determine whether the app currently has that permission. The compatibility library has already been encapsulated, just the following code:

int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,        Manifest.permission.WRITE_CALENDAR);

Returns packagemanager.permission_granted if the permission is available, otherwise returns Packagemanager. Permission_denied.

3.2. Request permission

When the application requires a permission, you can request permission, there will be a system standard dialog prompt request permission, this diolog can not be customized, the user agreed or rejected by the method Onrequestpermissionsresult () return results. When the user refuses to apply for this permission, re-apply dialog can be checked no longer prompt, in this case, the later request permission will not bounce Dialog direct return to reject. So some applications that rely on certain sensitive permissions need to be handled by themselves, explaining to the user why this permission is needed and convincing the user to grant permissions. The request permission code is as follows:

ActivityCompat.requestPermissions(thisActivity,                new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_CODE);
3.3. Handling Permission Request response

When the user processes the permission request, the system will callback the Onrequestpermissionsresult () method of the activity requesting the permission, and only need to override this method to get the return result

@Override Public void Onrequestpermissionsresult(intRequestcode, String permissions[],int[] grantresults) {Switch(Requestcode) { CaseMy_permissions_request_read_contacts: {//If request is cancelled, the result of arrays is empty.            if(Grantresults.length >0&& grantresults[0] = = packagemanager.permission_granted) {//permission was granted, yay! do the                //contacts-related task you need.}Else{//Permission denied, boo! Disable the                //functionality that depends on the this permission.}return; }    }}
3.4. Consider using intent

There are many permission actions to consider calling other apps, so the current app does not need permission to apply. For example, to get a camera photo, you can use the Action_image_capture to invoke the camera app to complete, the camera app will return the photo. You can also make calls, access contacts, and consider using a similar approach. This type of specialized application makes it easier for users to accept more than other applications.

4, about the domestic machine 6.0 system

Some domestic manufacturers have customized the system (such as Xiaomi, Huawei), and under 6.0 the system can control the permissions separately. However, usually they are not handled thoroughly enough, and when the code determines whether or not to authorize, the return is already authorized. And actually do the operation, but because there is no permission to cause the application crash. For example, I have encountered a scene:
* Access to the contact, you can get the cursor object, but Cursor.movetofirst () will return false.
* When accessing the camera, the acquired camera object is empty

So in the lower version of the mobile phone, do not assume that the system licensing is all right, must be more conditional interpretation and testing.

5, Permissiongrantor, a line of code to deal with dynamic permission application.

In the above runtime request permission, we see that the permission request relies on activity and fragment, and the use of the Startactivityforresult () method is similar and must depend on the activity and fragment callback methods. The requirements are normally met, but when the code for the requested permission is in a separate module, such as when I encapsulate a UI control, an action in the control requires permission, or the project takes the MVVM framework and requires permission in some view class or model class, it can be cumbersome to handle.
I encountered a similar situation in my own code, and later I used a separate activity to request permission to notify the business layer of authorization results by means of a callback. Feel very convenient to use, put it in the Maven warehouse, the project by adding the following dependencies can be.

‘com.github.dfqin:grantor:1.0.1‘
5.1 Permissiongrantor Use

The application permission is very simple, only needs the following sentence to be able.

PermissionsUtil.requestPermission(Activity activity, PermissionListener listener,     String[] permissions);

Here is an example of applying for a webcam:

Private void Requestcemera() {if(Permissionsutil.haspermission ( This, Manifest.permission.CAMERA)) {//have access to webcam}Else{Permissionsutil.requestpermission ( This,NewPermissionlistener () {@Override                 Public void permissiongranted(@NonNull string[] permissions) {//user granted permission to access the camera}@Override                 Public void permissiondenied(@NonNull string[] permissions) {//user denied access to the camera application}            },NewString[]{manifest.permission.camera}); }    }

Permissionsutil.requestpermission also has two overloads to implement. When a user denies authorization, a default dialog prompts the user to open the permission. This dialog content can be customized or not shown in this dialog, see GitHub for details. Have any questions welcome to discuss the exchange.

6. Reference
    • http://blog.csdn.net/qiujuer/article/details/44195131
    • Http://2dxgujun.com/post/2015/02/11/Publish-AAR-to-Maven-Central-with-Gradle.html?utm_source=tuicool&utm_ Medium=referral
    • Http://www.jianshu.com/p/dbe4d37731e6

Android 6.0 Runtime permissions analysis and Best practices

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.