Android 6.0+ Run-time permissions exploration

Source: Internet
Author: User

Original articles, reproduced please specify (from: http://blog.csdn.net/leejizhou/article/details/51511630 Li Zizhou blog)

Introduction: Last year, when Android 6.0 was released, its newly introduced (requesting Permissions at run time) runtime permissions were of interest to developers, With the popularity of the 6.0 system of domestic handset manufacturers this year, it is necessary to understand this new feature, because the development of targetsdk23+ does not pay attention to these will cause the app to run on the 6.0+ phone crash, this blog post will explore this new feature.

In the previous SDK development, if you need to use some permissions such as phone calls, text messages are only configured in Androidmanifest, but more than sdk23+ use a number of dangerous sensitive (dangerous Permissions) permissions are not just configured on the androidmanifest, you need to allow the user to grant permission before the operation can be done next, like the iOS permissions processing, If the user is not granted permission or the user denies the permission to do so, such as making a phone call can cause the software to crash.

* If your app targetsdk under 23 then run in 6.0+ system will not crash, of course, you can also TARGETSDK has been set under 23, then this article you do not need to continue to read:)

So what permissions do you need to authorize at run time? Look at the official instructions.

Dangerous permissions

These permissions need not only be configured in Androidmanifest, but also require the user to be granted permission at run time to use these features.

You can see that the call needs to be authorized at run time, we will make a click button to call the small demo, to see how this run-time permissions is going on.

1: Need to set the app's targetsdkversion to more than 23 and run the system above Android6.0

2: Configure the right to call in Androidmanifest

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

3: In layout layouts we simply put a button, click to make a call (slightly)

4.1: What happens if I do not do run-time permission handling? We directly click the button to make a call

  publicvoidCallPhone(View v) {        new Intent(Intent.ACTION_CALL);        Uri data = Uri.parse("tel:""10010");        intent.setData(data);        startActivity(intent);    }

Operating effect:

You can see that running on Android 6.0 system crashes

4.2: We add run-time permissions to process and run again

 Private Static Final intRequestcode =8; Public void Callphone(View v) {//Check Permissions        if(Contextcompat.checkselfpermission ( This, Manifest.permission.CALL_PHONE)! = packagemanager.permission_granted) {//No permissions, request permissionActivitycompat.requestpermissions ( This,NewString[]{manifest.permission.call_phone}, Requestcode); }Else{//already have permission to dialCall (); }    }

Api:
The role of Requestcode is to perform callback processing because the request permission is the result of a callback that will be said later.

Contextcompat.checkselfpermission is primarily used to detect whether a permission has been granted, the method parameter is (context, permission to be detected) method returns a value of Packagemanager.permission_ Denied or packagemanager.permission_granted, you need to invoke the API to request permission when returning to Packagemanager.permission_denied.

Activitycompat.requestpermissions for permission application, the method parameter is (context, need to request the permission array, custom request code), the system will pop up a request Permission dialog box.

Operating Effect:

You can see that the program has successfully dialed the phone.

4.3 But what if the user rejects the permission and sets a no longer alert? Click on the button will not respond, is very unfriendly, as follows.

Change the code slightly

  Public void Callphone(View v) {//Check Permissions        if(Contextcompat.checkselfpermission ( This, Manifest.permission.CALL_PHONE)! = packagemanager.permission_granted) {if(Activitycompat.shouldshowrequestpermissionrationale ( This, Manifest.permission.CALL_PHONE)) {NewAlertdialog.builder (mainactivity. This). Setmessage ("app needs to turn on permissions to use this feature"). Setpositivebutton ("Settings",NewDialoginterface.onclicklistener () {@Override                             Public void OnClick(Dialoginterface Dialoginterface,inti) {Intent Intent =NewIntent (settings.action_application_details_settings); Intent.setdata (Uri.parse ("Package:"+ Getpackagename ()));                            StartActivity (Intent); }}). Setnegativebutton ("Cancel",NULL). Create (). Show (); }Else{//Request PermissionActivitycompat.requestpermissions ( This,NewString[]{manifest.permission.call_phone}, Requestcode); }        }Else{//already have permission to dialCall (); }    }

Here we add a judgment before applying for permission Activitycompat.shouldshowrequestpermissionrationale (this,
Manifest.permission.CALL_PHONE) The method parameter is (context, the permission to be detected) if it returns true to prove that the user last clicked rejected, so we made some friendly hints, What is done here is to make a prompt and let the user jump to the settings to open the permission.

Operating Effect:

5:ok finally introduced, the application of the right callback method processing

 @Override     Public void Onrequestpermissionsresult(intRequestcode, @NonNull string[] permissions, @NonNullint[] grantresults) {Switch(Requestcode) { CaseRequestcode: {if(Grantresults.length >0&& grantresults[0] = = packagemanager.permission_granted) {//The user agrees to authorizeCall (); }Else{//user denied authorization                //Toast.maketext (Mainactivity.this, "Permission Denied", Toast.length_short). Show ();}return; }        }    }

This method is similar to Onactivityresult, first Judge Requestcode, then in the judgment of the user's authorization state, Grantresults array represents the result array of permissions, a bit around the mouth, haha, before the application permission is supported array, so Onrequestpermissionsresult return results are also placed in an array, array grantresults[n] = = packagemanager.permission_granted This permission has been authorized by the user.

Final: Finally, let's look at the complete code

/** * blog:www.lijizhou.com * * Public  class mainactivity extends appcompatactivity {    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);    Setcontentview (R.layout.activity_main); }Private Static Final intRequestcode =8; Public void Callphone(View v) {//Check Permissions        if(Contextcompat.checkselfpermission ( This, Manifest.permission.CALL_PHONE)! = packagemanager.permission_granted) {if(Activitycompat.shouldshowrequestpermissionrationale ( This, Manifest.permission.CALL_PHONE)) {NewAlertdialog.builder (mainactivity. This). Setmessage ("app needs to turn on permissions to use this feature"). Setpositivebutton ("Settings",NewDialoginterface.onclicklistener () {@Override                             Public void OnClick(Dialoginterface Dialoginterface,inti) {Intent Intent =NewIntent (settings.action_application_details_settings); Intent.setdata (Uri.parse ("Package:"+ Getpackagename ()));                            StartActivity (Intent); }}). Setnegativebutton ("Cancel",NULL). Create (). Show (); }Else{//Request PermissionActivitycompat.requestpermissions ( This,NewString[]{manifest.permission.call_phone}, Requestcode); }        }Else{//already have permission to dialCall (); }    }Private void Pager() {Intent Intent =NewIntent (Intent.action_call); Uri data = Uri.parse ("Tel:"+"10010");        Intent.setdata (data);    StartActivity (Intent); }@Override     Public void Onrequestpermissionsresult(intRequestcode, @NonNull string[] permissions, @NonNullint[] grantresults) {Switch(Requestcode) { CaseRequestcode: {if(Grantresults.length >0&& grantresults[0] = = packagemanager.permission_granted) {//The user agrees to authorizeCall (); }Else{//user denied authorization                //Toast.maketext (Mainactivity.this, "Permission Denied", Toast.length_short). Show ();}return; }        }    }}

OK, a use of Android Raw API run time permissions processing is finished, of course, you can also be packaged for easy use, welcome to the bottom of the message, this article source http://download.csdn.net/detail/leejizhou/9532629

Android 6.0+ Run-time permissions exploration

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.