Runtime dynamic authorization management

In the process of app development, operations involving hardware devices, such as taking pictures, recording, positioning, etc., must declare relevant permissions in AndroidManifest.xml. However, in order to prevent some apps from abusing permissions, the Android system allows users to disable certain permissions for apps in the system settings. However, this brings another problem. After the user opens the app, the app may not run properly due to insufficient permissions, or even crash and crash directly. In this case, the user only needs to enable the relevant permissions in the system settings to return to normal, but the user is not a professional developer, how does he know which permissions to enable? Besides, every time the user needs to open the system settings page in person, and then spend a long time carefully selecting the permissions that must be enabled, it is not only labor-intensive but also labor-intensive. This kind of user experience is really bad.

In view of this, Android has introduced a runtime permission management mechanism since 6.0, which allows the App to dynamically check whether it has a certain permission during the running process. Once a necessary permission is found to be missing, the system will automatically pop up a small window to prompt the user to open it. this permission. In this way, on the one hand, developers don't need to worry about the app crashing due to insufficient permissions, and on the other hand, users no longer have to worry about which permission is forbidden to make the app unusable. This intimate dynamic permission authorization function can be said to be everyone's delight. . Let's take a look at how to implement the runtime permission management mechanism in the code.

The first thing to check is whether the Android system is version 6.0 and above, because the runtime permission management mechanism is a function that was only supported by 6.0. Next, call the ContextCompat.checkSelfPermission method to check whether the current App has the specified permission enabled. If the result of the check is that the permission has not been enabled, then call the ActivityCompat.requestPermissions method to request the system to pop up a confirmation dialog box for enabling the permission. The detailed permission verification code is as follows:

    // 检查某个权限。返回true表示已启用该权限,返回false表示未启用该权限
    public static boolean checkPermission(Activity act, String permission, int requestCode) {
        Log.d(TAG, "checkPermission: "+permission);
        boolean result = true;
        // 只对Android6.0及以上系统进行校验
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查当前App是否开启了名称为permission的权限
            int check = ContextCompat.checkSelfPermission(act, permission);
            if (check != PackageManager.PERMISSION_GRANTED) {
                // 未开启该权限,则请求系统弹窗,好让用户选择是否立即开启权限
                ActivityCompat.requestPermissions(act, new String[]{permission}, requestCode);
                result = false;
            }
        }
        return result;
    }

For example, if the App is going to take a picture now, you need to check whether the camera permission Manifest.permission.CAMERA is enabled. If the camera permission is not enabled, the system will pop up the selection window shown in the figure below.

For another example, if the App is going to obtain the location information of the mobile phone, it needs to check whether the positioning permission Manifest.permission.ACCESS_FINE_LOCATION is enabled. If the positioning is not enabled, the system will pop up the selection window shown in the figure below.

Notice that there are two buttons "Deny" and "Allow" in the permission selection pop-up window of the system, which means that the developer has to deal with the two options separately. If the user clicks the "Reject" button, it naturally means that the App will not run normally. At this time, the user needs to be reminded of the possible problems and their reasons; if the user clicks the "Allow" button, the system will immediately give the App the corresponding permissions. Then the app goes on according to the normal process, taking pictures when it is time to take a picture, and positioning it when it needs to be positioned. The above option judgment logic, specific to the code, needs to rewrite the onRequestPermissionsResult function of the Activity. The rewritten function code example is as follows:

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == mRequestCode) { // 通过requestCode区分不同的请求
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 已授权,则进行后续的正常逻辑处理
            } else {
                Toast.makeText(this, "需要允许相机权限才能拍照噢", Toast.LENGTH_SHORT).show();
            }
        }
    }

Sometimes a certain business must enable multiple permissions at the same time. For example, for video recording, both the camera permission and the recording permission must be enabled. Then when verifying permissions, the ContextCompat.checkSelfPermission method needs to be called multiple times. Only when all the permissions to be checked have been authorized, there is no need for a system pop-up prompt; otherwise, the system still needs to pop up one by one for the user to select and confirm. The following is a code example to verify multiple permissions at the same time, where multiple permissions are passed in "new String[] {Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA}" in the form of a string array parameter:

    public static boolean checkMultiPermission(Activity act, String[] permissions, int requestCode) {
        boolean result = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int check = PackageManager.PERMISSION_GRANTED;
            // 通过权限数组检查是否都开启了这些权限
            for (String permission : permissions) {
                check = ContextCompat.checkSelfPermission(act, permission);
                if (check != PackageManager.PERMISSION_GRANTED) {
                    break;
                }
            }
            if (check != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(act, permissions, requestCode);
                result = false;
            }
        }
        return result;
    }

Still taking the video recording business as an example, if the App has neither camera permission nor recording permission, after using the runtime permission management mechanism, the system will pop up the recording permission selection window and the camera permission selection window in turn on the interface. The screenshots of the two permission pop-ups are shown below:

Recording permission selection window

Camera permission selection window

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325363190&siteId=291194637