Android M Permission learning notes, androidpermission

Source: Internet
Author: User

Android M Permission learning notes, androidpermission

Android M Permission learning notes Brief Introduction to Android Application PermissionsBy default, an Android application does not have any permissions. That is to say, by default, an application does not have the right to perform operations that may cause adverse effects. these negative effects may be on other applications, operating systems, or users. if the application requires some additional capabilities, it must be in AndroidManifest. the corresponding permissions are declared statically in xml. if the application does not declare the permission in manifest but uses the corresponding function, an exception is thrown when the corresponding function is called. for example, if the program wants to send a request but forgets to add Internet permissions, the program will throw an exception when sending the request, and will not catch the exception, so the program will crash directly: Caused by: java. lang. SecurityException: Permission denied (missing INTERNET permission ?)In Android 6.0 (API 23)Before the release, all permissions are displayed to the user when the application is installed. If you select the installation option, all permissions are accepted and cannot be revoked. at the beginning of Android 6.0, some dangerous permissions need to be explicitly displayed when the program is running, requesting user authorization. it is up to the application to decide when to play this box. other permissions are considered to be not very dangerous. Therefore, we still keep the original practice and authorize the user when installing the application. it should also be noted that, in settings, users can selectively authorize or disable dangerous permissions of applications. Permission Protection LevelPermission protection levels are set through the protectionLevel attribute. There are four types: Normal, dangerous, signature, signatureOrSystem.For details, see Introduction: http://developer.android.com/guide/topics/manifest/permission-element.html signature is not commonly used, the remaining two are NormalAnd Dangerous. The two types are discussed in Guides: All permissions of Guides on the official website are still declared in manifest. normal permissions are automatically authorized during installation, the permission of dangerous requires the application to explicitly request user authorization. of course, the dangerous permission is also authorized during installation for mobile phones lower than Android 6.0 or old applications that were previously developed. For details, refer to the following section. dangerous Permissions:

Table 1.Dangerous permissions and permission groups.

Permission Group 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
To view all the permissions of dangerous, run the following command: Adb shell pm list permissions-g-d Handling different mobile phone versions and program versionsHere we reference the original article in Guildes:
  • If the device is running Android 6.0 (API level 23) or higher,AndThe app'stargetSdkVersionIs 23 or higher, the app requests permissions from the user at run-time. the user can revoke the permissions at any time, so the app needs to check whether it has the permissions every time it runs. for more information about requesting permissions in your app, see the Working with System Permissions training guide.
  • If the device is running Android 5.1 (API level 22) or lower,OrThe app'stargetSdkVersionIs 22 or lower, the system asks the user to grant the permissions when the user INSTALLThe app. if you add a new permission to an updated version of the app, the system asks the user to grant that permission when the user updates the app. once the user INSTALLThe app, the only way they can revoke the permission is by uninstalling the app.
Pay attention to the use of and or, which indicates that only TargetSdkVersionAnd the actual version of the device is 23 or above, the new dynamic permission mechanism will be used. in other cases, as before, all permissions are granted during application installation and upgrade. It can be summarized:1. all permissions are declared in manifest. 2. if (1) your app's targetSdkVersion is 23 or above and (2) the app runs on Android 6.0 or above devices, dangerous permissions must be dynamically requested. when the permission is denied, the app should still be able to use it, but some permissions related functions cannot be used. 3. the two conditions (1) in the previous section (2) are not met at the same time. In other cases, all permissions are requested during installation. If the user does not accept these conditions, the installation is not performed. Pay special attention to this situation: the old application of the new system.If targetSdkVersion is less than 23, it is considered to be an application developed before Android 6.0 is released and is not compatible with Android 6.0. Even if the application is installed on Android 6.0, it uses the original installation and permission granting logic.All permissions are granted during application installation. after the targetSdkVersion is installed on Android 6.0, you can check the application settings and find that all dangerous permission statuses are enabled. therefore, you don't have to worry that the old applications will crash in the Android 6.0 environment. however, you can still disable permissions in system settings: When you click the authorization switch on the simulator, the following prompt is displayed: if the user insists on canceling authorization, the application will not crash directly, however, the function changes to the silent status, and the returned value may be null or 0, causing unexpected behavior or crash. Why do you need to upgrade targetSdkVersion in time?This is because each version of the API may generate new permissions. These new permissions are automatically obtained for applications with lower targetSdkVersion than this API. therefore, it is best to write targetSdkVersion to the latest version in time, so that the application does not automatically obtain the new permissions of the new API. conclusion: permissions that do not exist in targetSdkVersion are automatically obtained. for details, see the section "Custom automatic permission adjustments" in API Guides: https://developer.android.com/guide/topics/security/permissions.html. Permission groupAll permissions have their own permission group. when a user requests a permission, the system only specifies its category. When the user agrees, the system will give the permission. (Only this one ). however, if the app already has another permission under the group, the system will automatically grant the permission (that is, the callback of the Request permission will return directly), which does not interact with the user. Implementation of Dynamic permission requestsOriginal article: compatible 6.0 is added. if minSdkVersion is not 23, SupportLibrary is recommended. The advantage is that if is not added to the program to determine the current device version. 1. Check the permission statusIf a dangerous permission is required for the operation, you must check whether the permission exists at the place where the operation is executed, because the user can change the authorization situation freely in the application settings, therefore, you must check whether you have the permission before use. how to check permissions: ContextCompat. the checkSelfPermission () parameters are Context and permission names. the returned value is: PERMISSION_GRANTEDIf you have the permission, or PERMISSION_DENIEDIf not. For example:
if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS)) {    //has permission, do operation directly    ContactsUtils.readPhoneContacts(this);    Log.i(DEBUG_TAG, "user has the permission already!");} else {    //do not have permission
 
2. Dynamic Request PermissionsIf the above permission check result is DENIED, You need to explicitly request this permission to the user. android provides several methods to dynamically request permissions. Calling these methods will display a standard Dialog, which cannot be customized currently. 2.1 sometimes you may need to explain why you need this permission.Sometimes you may need to explain the purpose of the permission to the user. note that not all permissions need to be explained. Obviously, too many interpretations will reduce the user experience. one way is that when the user rejects this permission but uses this function again, the user may not quite understand why the app needs this permission, at this time, you can explain it to the user first. android provides a tool class method: shouldShowRequestPermissionRationale (). If the app has previously requested this permission and is denied by the user, this method returns true. if you have selected the "Don't ask again" option in the dialog box before rejecting permissions, this method returns false. if the device policy disables the application from having this permission, This method also returns false. note that the dialog must be implemented by yourself. The system does not provide the dialog. 2.2 request PermissionsRequest permission: requestPermissions () is used to input an Activity, an array of permission names, and an integer request code. this method is asynchronous and will return immediately. After the user interacts with the dialog, the system will call the callback method to return the user's selection result and the corresponding request code. code:
if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS)) {    //has permission, do operation directly    ContactsUtils.readPhoneContacts(this);    Log.i(DEBUG_TAG, "user has the permission already!");} else {    //do not have permission    Log.i(DEBUG_TAG, "user do not have this permission!");    // Should we show an explanation?    if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,            Manifest.permission.READ_CONTACTS)) {        // Show an explanation to the user *asynchronously* -- don't block        // this thread waiting for the user's response! After the user        // sees the explanation, try again to request the permission.        Log.i(DEBUG_TAG, "we should explain why we need this permission!");    } else {        // No explanation needed, we can request the permission.        Log.i(DEBUG_TAG, "==request the permission==");        ActivityCompat.requestPermissions(MainActivity.this,                new String[]{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.    }}
This dialog box is system and cannot be customized. after verification, the "Don't ask again" option in the request permission dialog box appears only when the status before the permission is Denied. I have never been authorized before (that is, the first pop-up box), or the previous status is Granted (of course, in this case, I usually do not ask in the box ), the displayed dialog box does not contain the option that you do not need to ask again. 2.3 response to request PermissionsThe system calls onRequestPermissionsResult()Method to return the user's response. in this callback, the request code is the parameter passed in when requestPermissions () is called. It is an integer value customized by the app. if the request is canceled, the returned array is empty. code:
@Overridepublic void onRequestPermissionsResult(int requestCode,                                       String permissions[], int[] grantResults) {    switch (requestCode) {        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {            // If request is cancelled, the result arrays are empty.            if (grantResults.length > 0                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {                // permission was granted, yay! Do the                // contacts-related task you need to do.                ContactsUtils.readPhoneContacts(this);                Log.i(DEBUG_TAG, "user granted the permission!");            } else {                // permission denied, boo! Disable the                // functionality that depends on this permission.                Log.i(DEBUG_TAG, "user denied the permission!");            }            return;        }        // other 'case' lines to check for other        // permissions this app might request    }}
Automatic System callback:In some cases, call 1. automatic authorization: If you have already granted the permission in the permission group, the system will directly call the requestPermissions () method to request the B permission in the same group next time. onRequestPermissionsResult()Callback method, and return the result of PERMISSION_GRANTED. 2. automatic Rejection: if you choose not to ask for this permission, when the app calls the requestPermissions () method again to request the same permission, the system will directly call the onRequestPermissionsResult () callback and return PERMISSION_DENIED. demo address: https://github.com/mengdd/AndroidMRuntimePermissionSample Best PracticesSummary of https://developer.android.com/training/permissions/best-practices.htmlBest Practices: 1. start other applications with Intent to complete functions. 2. only the required permissions are required. 3. do not bother users by requesting Multiple permissions at a time. Some permissions can be requested again when they are to be used. 4. explain to the user why this permission is required. 5. from Android 6.0, each permission must be tested and switched to make the application run normally, rather than crashing. in addition, the related permissions may need to be tested in different combinations. ADB commandYou can Use the command line to manage permissions: Use the adb tool to manage permssions from the command line:
  • List permissions and status by group:

    $ Adb shell pm list permissions-d-g

  • Grant or revoke one or more permissions:$ Adb shell pm [grant | revoke] <permission-name>... 
References:API Guides: https://developer.android.com/training/permissions/index.htmlRuntime permissions: https://source.android.com/devices/tech/config/runtime_perms.htmlpermission element: http://developer.android.com/guide/topics/manifest/permission-element.html design Patterns-> Permissions: https://www.google.com/design/spec/patterns/permissions.html blog post: http://jijiaxin89.com/2015/08/30/Android-s-Runtime-Permission/ third-party Library: PermissionsDispatcher: https://github.com/tbruyelle/RxPermissions http://www.cnblogs.com/mengdd/p/4892856.html address:

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.