Android permission permissions and security mechanism analysis (next)

Source: Internet
Author: User

In the Android permission permissions and security mechanism resolution (i) blog, I have described in detail the Android related system permission and custom permission, as well as some of the permissions mechanisms and security mechanisms. This blog will mainly introduce the relevant permissions changes, principles and related processing methods, solutions , etc. for Android 6.0.
I used to imitate the latest version of the album as an example to analyze.

Android 6.0 permissions comprehensive detailed analysis and solutions Marshmallow version Permissions modification

The Android privilege system has always been the primary security concept because these permissions are only asked once during installation. Once installed, the app can access everything in the right without the user's knowledge, and the average user rarely has to look at the list of permissions when it's installed, not to get a deeper understanding of the risks associated with these permissions. Therefore, after the Android 6.0 Marshmallow version, the system will not give the app all its application permissions when the software is installed, for some dangerous level of permissions, the app needs to be at runtime one to ask the user to grant permissions.
  

Old version app compatibility issues

So the question is, is there a problem with all the previously released apps? The answer is no, only those targetsdkversion set to 23 and more than 23 of the application will be abnormal, when the use of dangerous permissions, the system must obtain the user's consent to use, or the application will crash, there are similar

java.lang.SecurityException:com.android.providers.media.MediaProvider

The crash log. So if Targetsdkversion is not set to 23 or above, the system will still use the old rule: give all the permissions that the app applies to when it's installed. So, of course, the app can be as normal as before, but there is a point to note that 6.0 of the system, the user can manually close the app's permissions , such as
  
So again, if the permissions of the old application request were manually closed by the user, what would the application crash? Let's give it a try.
  
OK, you can be thankful for a bit, will not throw an exception, will not crash, just call those who are prohibited by the user API interface return value is null or 0, so we just need to do a short operation on the empty, and will certainly collapse.

General permissions and Dangerous permissions list

Now for the new version of the permission changes should have a basic understanding, then, is not all permissions need to go to special processing it? Of course not, only those dangerous levels of permissions are needed, as the list shows:
  
The Android Developer Official website also has the relevant description:
Http://developer.android.com/training/permissions/requesting.html
Http://developer.android.com/guide/topics/security/permissions.html#normal-dangerous
So take a closer look at your app, against the list, and if you need to apply for one of these permissions, you need to do something special. There's a more humane place to be. If any one of the permissions in the same group is authorized, the other permissions are automatically authorized. For example, once write_external_storage is authorized, the app also has read_external_storage permissions.

Support Marshmallow new version permission mechanism

Finally to start supporting the Android 6.0 version, the first step is of course to modify the Build.gradle file Tragetsdkversion and compilesdkversion into 23 versions, while using compile ' com.android.support:appcompat-v7:23.1.1 ' latest V7 pack.

android {    23    ...    defaultConfig {        ...        23        ...    }}...dependencies {...‘com.android.support:appcompat-v7:23.1.1‘...

After the modification, interested friends can be packaged directly on the phone to test, to see if there will be similar to the above I said that the crash log.
Then of course the next step is to modify the code, the most primitive code, no processing:

private void Startgetimagethread () {.... Uri uri = Mediastore. Images. Media. EXTERNAL_content_uri;Contentresolver contentresolver = Getcontentresolver ();Get files in JPEG and PNG format and reverse by TIME cursor cursor = Contentresolver. Query(URI, NULL, Mediastore. Images. Media. MIME_type +" =\" image/jpeg\ "or"+ Mediastore. Images. Media. MIME_type +" =\" image/png\ "", NULL, Mediastore. Images. Media. DATE_modified+"desc");....}

This code requires access to external storage (photo album), which is a dangerous level of privilege, and direct use will cause the app to crash, so we need to do special processing before this code executes:

int hasWriteContactsPermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {        requestPermissions(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},                CODE_FOR_WRITE_PERMISSION);    return;}

After writing this code, the following system dialog appears:

The callback for deny and allow is then required, overriding the Onrequestpermissionsresult function:

@OverridepublicvoidonRequestPermissionsResult(intint[] grantResults) {    if (requestCode == CODE_FOR_WRITE_PERMISSION){        if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)            &&grantResults[0] == PackageManager.PERMISSION_GRANTED){            //用户同意使用write            startGetImageThread();        }else{            //用户不同意,自行处理即可            finish();        }    }}

Okay, so it's a simple preliminary adaptation.

Handling no More reminders

If the user rejects an authorization. The next time the box is played, the user will have a "no longer reminded" option to prevent the app from continuing to request authorization later.
  
If this option is checked by the user before the authorization is denied. The next time for this permission to request Requestpermissions, the dialog box will not pop out, the system will directly callback the Onrequestpermissionsresult function, the callback result is the last user's choice. So in order to deal with this, the system provides a shouldshowrequestpermissionrationale () function that helps developers find situations that require additional explanation of permissions to the user, a function that:

    1. Apply the first access after installation, directly return false;
    2. The first time the permission is requested, the user rejects, the next time Shouldshowrequestpermissionrationale () returns True, this can show some explanation of why this permission is required;
    3. The second time the permission is requested, the user rejects, and the option "no longer reminded" is selected: Shouldshowrequestpermissionrationale () returns false;
    4. The device's system settings prohibit the current app from obtaining authorization for this permission, Shouldshowrequestpermissionrationale () returns false;
Note: The second time you request permission, there will be a "no longer alert" option, if the user has been refused, and did not select the "no longer remind" option, the next time the permission is requested, will continue to have "no reminder" option, and Shouldshowrequestpermissionrationale ( ) will also always return true.
So with this function we can do the corresponding optimization, there are two ways to return false for the Shouldshowrequestpermissionrationale function:
    • If the application is the first time the permission is requested, then call the Requestpermissions function directly to request permission, if not on behalf of the user ticked ' no reminder ', pop-up dialog, tell the user why you need this permission, let the user manually open the permission. Links: http://stackoverflow.com/questions/32347532/ Android-m-permissions-confused-on-the-usage-of-shouldshowrequestpermissionrati
    • In the Onrequestpermissionsresult function, if the permission_denied is returned, the Shouldshowrequestpermissionrationale function is called, If the return false means that the user has disabled the permission (3 and 42 cases above), pop-up dialog tells the user why you need the permission and lets the user open it manually. Links: Http://stackoverflow.com/questions/30719047/android-m-check-runtime-permission-how-to-determine-if-the-user-checked-nev
The processing method already has, modifies the code, I here takes the second kind of solution to deal with:

@Override Public void Onrequestpermissionsresult(intRequestcode, string[] permissions,int[] grantresults) {if(Requestcode = = code_for_write_permission) {if(permissions[0].equals (Manifest.permission.WRITE_EXTERNAL_STORAGE) &&grantresults[0] = = packagemanager.permission_granted) {//user agrees to use writeStartgetimagethread (); }Else{//user does not agree to show the user the role of this permission            if(! Activitycompat.shouldshowrequestpermissionrationale ( This, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {Alertdialog dialog =NewAlertdialog.builder ( This). Setmessage ("The album needs to give access to the store permissions, do not turn on will not work properly!" "). Setpositivebutton ("OK",NewDialoginterface.onclicklistener () {@Override                             Public void OnClick(Dialoginterface Dialog,intwhich) {finish (); }}). Setnegativebutton ("Cancel",NewDialoginterface.onclicklistener () {@Override                             Public void OnClick(Dialoginterface Dialog,intwhich) {finish ();                }}). Create (); Dialog.show ();return;        } finish (); }    }}

When the tick is no longer reminded and rejected, pop-up dialog to remind the user of the importance of this privilege:
  
Get!!!

Using the Compatibility library

The above code in the 6.0 version of the use of no problem, but before there is a problem, the most simple and rough solution may be the use of Build.VERSION.SDK_INT >= 23 judgment statement to judge, convenient is the SDK 23 of the V4 packages are joined by specialized classes for related processing:

    • Contextcompat.checkselfpermission ()
    • The authorized function returns permission_granted, otherwise it returns permission_denied, which is true for all versions.
    • Activitycompat.requestpermissions ()
    • This method is called before 6.0, and Onrequestpermissionsresultcallback is called directly, with the correct permission_granted or permission_denied.
    • Activitycompat.shouldshowrequestpermissionrationale ()
    • Before 6.0, the version is called, and always returns false.
With the V4 package, these three methods are perfectly compatible with all versions! Here's the code:

//use the compatibility library without judging the system version int haswritecontactspermission = Contextcompat.checkselfpermission  (Getapplication (), Manifest.permission   _external_storage) ;  if (haswritecontactspermission = = Packagemanager. PERMISSION  _granted) {startgetimagethread () ; } Need to eject dialog let the user manually give permission else{activitycompat.requestpermissions  ( Pickortakeimageactivity.this , new String[]{manifest.permission   _external_storage}, code_for_write_permission) ; }  

The Onrequestpermissionsresult function does not change. The latter two methods, we can also use in the fragment, with the V13 Compatibility Pack: Fragmentcompat.requestpermissions () and Fragmentcompat.shouldshowrequestpermissionrationale () is the same as the activity effect.

Request multiple permissions at once

Of course, multiple permissions are sometimes required, and multiple permissions can be requested one time using the method above. Of course, the most important thing is not to forget to check the "No reminder" setting for each permission.

list<string> permissionsneeded = new arraylist<string> ()  Permissionsneeded.add  (Manifest  _fine_location) ;  Permissionsneeded.add  (Manifest  _contacts) ;  Permissionsneeded.add  (Manifest  _contacts) ;  Requestpermissions (Permissionsneeded.toarray  (New string[permissionslist< Span class= "Hljs-preprocessor" >.size  ()]), code_for_multiple_permission) ;  

Finally, the Onrequestpermissionsresult function is processed to return the result.

Third-party Library simplified Code

Of course, there are third-party libraries to help with these things:
Open source projects on GitHub Permissionhelper and Hotchemi ' s Permissionsdispatcher

The app is in the running state, revoked the permission

What happens if the app is running and the user goes to the Settings-application page to manually revoke the app permissions? Haha, the system will then pop up the Permission Request dialog box, very good very good:
  
So there's no problem. O (∩_∩) o~
The above test environment for the genymotion6.0 simulator, a friend and I reflect on the 6.0nexus 6p real machine will exit the application directly, so this should also be related to the test environment.

Conclusion recommendations

New run-time permissions are already in use in cotton candy. We have no retreat. The only thing we can do now is make sure the app is adapting to the new permissions model. Thankfully, only a few permissions require a run-time permission model. Most commonly used permissions, such as network access, that belong to normal Permission are automatically authorized at the time of installation, and of course you want to declare that you do not need to check later. Therefore, only a small part of the code you need to modify.
Two recommendations:
1. Take the new permissions model seriously.
2. If your code does not support new permissions, do not set targetsdkversion 23. Especially when you're building a new project in studio, don't forget to change it!
Talk about code modifications. This is a big deal, and if the code structure is not well designed, you need some very painful refactoring. Each app has to be fixed. As mentioned above, we have no choice. List all the circumstances in which you need to request permission, if A is authorized, B is rejected, what happens, and is handled carefully for each situation.

Cite articles

Http://www.jianshu.com/p/e1ab1a179fbb
Http://blog.csdn.net/yangqingqo/article/details/48371123
http://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en
Http://developer.android.com/training/permissions/requesting.html
Http://developer.android.com/guide/topics/security/permissions.html#normal-dangerous
Http://developer.android.com/reference/android/support/v4/app/ActivityCompat.html

Android permission permissions and security mechanism analysis (next)

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.