First, why to apply for permission dynamically

Android6.0 in order to protect user privacy, some permission applications in the application running time to apply. Before Android6.0, developers only needed to declare the permissions in the androidmanifest.xml file. Some apps declared all kinds of permissions, and users could install them without looking carefully, so these apps could do whatever they wanted. Android6.0 divides permissions into normal permissions and dangerous permissions. The normal permissions declared in AndroidManifest will be automatically granted, while dangerous permissions need to be explicitly granted by users when they are used.

In other words, the system above Android 6.0 needs to apply to the user for the first time when using the dangerous permission, and obtain the user’s consent. If still in no Permission to perform the operation, the system will Crash, the error log for Java. Lang. SecurityException: Permission “. Therefore, the application for dangerous permission must be handled accordingly.

Ii. Special Permissions (dangerous permissions)

Users need to apply for these permissions dynamically when using them. For example, when the user opens the camera to take photos, the developer needs to apply for permission at the place where the camera is opened through code. Permissions in Android6.0 developers need to pay attention to:

1. Due to the permissions API, our Actiivty should be of the AppCompatActivity type, which means your BaseActivity needs to inherit AppCompatActivity.

2. Permissions are grouped. If the same group of permissions applies for one of them, all permissions of the same group are applied for. For example, after an application is granted the READ_EXTERNAL_STORAGE permission, if it applies for the WRITE_EXTERNAL_STORAGE permission, the system grants the permission immediately, and no permission grant dialog box is displayed.

(I) Special Permission Group (9 groups in total)

I have no choice but to have a MICROPHONE, such as recording PHONE, PHONE status, SENSORS, SMS, STORAGECopy the code

The following are the permissions that need to be applied separately. There are nine groups of permissions. If one group of permissions is applied successfully, the whole group of permissions can be used by default:

#### group:android.permission-group.CALENDAR
permission:android.permission.READ_CALENDAR
permission:android.permission.WRITE_CALENDAR

#### group:android.permission-group.CAMERA
permission:android.permission.CAMERA

#### group:android.permission-group.CONTACTS
permission:android.permission.WRITE_CONTACTS
permission:android.permission.GET_ACCOUNT
permission:android.permission.READ_CONTACTS

#### group:android.permission-group.LOCATION
permission:android.permission.ACCESS_FINE_LOCATION
permission:android.permission.ACCESS_COARSE_LOCATION

#### group:android.permission-group.MICROPHONE
permission:android.permission.RECORD_AUDIO

#### group:android.permission-group.PHONE
permission:android.permission.READ_CALL_LOG
permission:android.permission.READ_PHONE_STATE
permission:android.permission.CALL_PHONE
permission:android.permission.WRITE_CALL_LOG
permission:android.permission.USE_SIP
permission:android.permission.PROCESS_OUTGOING_CALLS
permission:com.android.voicemail.permission.ADD_VOICEMAIL

#### group:android.permission-group.SENSORS
permission:android.permission.BODY_SENSORS

#### group:android.permission-group.SMS
permission:android.permission.READ_SMS
permission:android.permission.RECEIVE_WAP_PUSH
permission:android.permission.RECEIVE_MMS
permission:android.permission.RECEIVE_SMS
permission:android.permission.SEND_SMS
permission:android.permission.READ_CELL_BROADCASTS

#### group:android.permission-group.STORAGE
permission:android.permission.READ_EXTERNAL_STORAGE
permission:android.permission.WRITE_EXTERNAL_STORAGE

Copy the code

(2) The correct posture of applying for permission

Step 1: set targetSdkVersion to 23. If targetSdkVersion is set to >=23, you must dynamically apply for permissions according to Google’s requirements.

Step 2: All permissions that need to be applied are declared in the AndroidManifest file, including ordinary permissions and special permissions.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Copy the code

Step 3: Check permission when using, and apply for no permission. There are two processes:

  • Process 1

Check if this permission checkSelfPermission() is enabled. If you have this permission, do what you want directly. Have this permission, apply to the system for this permission;

 if(ContextCompat.checkSelfPermission(getApplication(), The Manifest. Permission. WRITE_EXTERNAL_STORAGE) = = PackageManager. PERMISSION_GRANTED) {/ / have permissions, Do what you want to doyourSelfSomething(); }else{// No permission is enabled, Apply to the system permissions ActivityCompat. RequestPermissions (activity, new String [] {the Manifest. Permission. WRITE_EXTERNAL_STORAGE}, MyApplication.CODE_FOR_WRITE_PERMISSION); }Copy the code
  • Process 2

If not enabled, go to the system and requestPermissions(). The user agrees to enable the permission, then continue to do what they want to do.

If the user does not agree to enable the permission, the text description of the permission is displayed to the user. Users click OK button, continue to apply for this permission to the system, a kind of circular authorization flavor, do not open this permission, do not let the use of this function.

User does not agree to open access has the following three conditions, shouldShowRequestPermissionRationale way of judgment.

ShouldShowRequestPermissionRationale method return values are: 1, request the permissions for the first time, to returnfalse. 2. If the user denies the request, returntrue. (The example is this case, generally this case, as long as you do not check no reminder, will always ask whether the permission is opened) 3. If the user has requested the permission, but the user refuses to check no reminder, returnfalse.Copy the code
@Override public void onRequestPermissionsResult(int requestCode, String[] permissions, Int [] grantResults) {// Identify the same request by requestCodeif (requestCode == MyApplication.CODE_FOR_WRITE_PERMISSION){
            if(grantResults. Length > 0 && grantResults [0] = = PackageManager. PERMISSION_GRANTED) {/ / user agrees to open access, Do doyourSelfSomething(); }else{// If the user disagrees, show the function and necessity of the permission to the user. The user clicks OK to apply for the permission to the system.if(ActivityCompat shouldShowRequestPermissionRationale (this,  Manifest.permission.WRITE_EXTERNAL_STORAGE)) { new AlertDialog.Builder(TestActivity.this) .setMessage("This permission is used to cache the image of the first page to your local, the next time you use the image, no network request.")
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    ActivityCompat.requestPermissions(this, 
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                    MyApplication.CODE_FOR_WRITE_PERMISSION);
                                }
                            })
                            .setNegativeButton("Cancel", null)
                            .create()
                            .show();
                }else{/ / this kind of circumstance is, shouldShowRequestPermissionRationale 1 and 3, the default don't do processing, according to the need of the development needs it}}}}Copy the code

(3) Points needing attention

1. CheckSelfPermission: Checks whether the permission is enabled.

A dialog box will pop up asking the user whether to enable the permissions.

ShouldShowRequestPermissionRationale: Android native system, pop-up permissions dialog application, if the first refused, can appear the second time doesn’t pop up “after” the prompt dialog box. If the user checked again, the user application permissions, shouldShowRequestPermissionRationale returns true, mean to give users an explanation, tell the user why the permissions.

However, in the actual development, a lot of mobile phones have modified on the native system, such as millet, huawei and so on some models of 6.0 shouldShowRequestPermissionRationale has returns false, at the right time, if the user selects a rejected, then won’t pop-up dialog again next time, In order not to annoy users. On my Mi 6 mobile phone 7.0, if the user chooses to reject the application right limit, the application right dialog box will pop up again next time. So the same brand of mobile phone, different versions of manufacturers have done different processing.

My solution is to deal with it in the callback. If the user rejects the permission, the pop-up box will prompt to explain the function of the permission, and then open the application information interface. The user can manually open the permission or apply for the permission again with the code.

4. It is suggested that each application should have its own permission management interface, which contains the permissions applied for by the application and various states. Even if the user has agreed to the permissions applied by you, he can close it at any time.

5. You can use the third-party library for permission application, which should be available online.

Common permissions

The following are only common permissions, normal use of development time on the line, the required permissions can be configured in the manifest file.

ACCESS_LOCATION_EXTRA_COMMANDS Location permission ACCESS_NETWORK_STATE Network status permission ACCESS_NOTIFICATION_POLICY Notification APP notifications are displayed in the status bar BLUETOOTH BLUETOOTH permission BLUETOOTH_ADMIN BLUETOOTH switch BROADCAST_STICKY broadcast CHANGE_NETWORK_STATE Changes the network status CHANGE_WIFI_MULTICAST_STATE Changes the WiFi multicast state. It controls the phone's hotspot. CHANGE_WIFI_STATE controls the WiFi switch. Change WiFi status DISABLE_KEYGUARD Change the keyboard to unavailable EXPAND_STATUS_BAR Extend bar status GET_PACKAGE_SIZE Obtain the size of the application installation package INTERNET network permission KILL_BACKGROUND_PROCESSES Kills background processes MODIFY_AUDIO_SETTINGS Changes audio output Settings NFC payment READ_SYNC_SETTINGS Obtains mobile phone Settings READ_SYNC_STATS Statistics RECEIVE_BOOT_COMPLETED Listens to start broadcast REORDER_TASKS Creates a new stack REQUEST_INSTALL_PACKAGES installs the application SET_TIME_ZONE allows applications to set system time zones SET_WALLPAPER_HINTS Sets the hints on the wallpaper, Personalized language TRANSMIT_IR Infrared emission USE_FINGERPRINT Fingerprint identification VIBRATE WAKE_LOCK Screen lock WRITE_SYNC_SETTINGS Change Settings SET_ALARM Setting Warning prompt INSTALL_SHORTCUT Create shortcut UNINSTALL_SHORTCUT Delete shortcutCopy the code