Application of dynamic permissions in Android

In the previous blog, I talked about how to encapsulate a dynamic permission base class. However, many readers may still not know how to apply for dynamic permissions. I just read the book and saw this, I will also summarize it.

request for access

public static boolean checkPermission(Activity act,String permission,int requestCode){
    boolean result = true;
    //只对Android 6.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;
}

Callback after permission application

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == mRequestCode){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                //已授权,则进行后续的正常逻辑处理
                ToastUtil.toastWord(this,"授权了");
            }else{
                //未授权,则提示用户可能导致的问题
                ToastUtil.toastWord(this,"没授权");
            }
        }
    }

Finally, we call the method of checking permissions and pass in the identification code mRequestCode

checkPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE,mRequestCode);

Of which identification code

private final int mRequestCode = 1001;//定义的请求权限识别

Here to explain, when we determine that the user has not obtained the permission, we will make a request. At this time, the phone will pop up a box to ask the user whether to authorize. If the user is authorized, we enter the callback to prompt that the authorization is successful, there is nothing to say about this. If the user is prohibited from entering, we enter the unauthorized judgment of the callback, and the user still pops up when the user applies again, which is also possible.

But when the user has checked the prohibition, do not ask again, and then click prohibition. Then the problem is big, because in the future, you will not enter the box directly without authorization. So if we have this situation, we must make relevant judgments and let the user enter the settings page to make the corresponding settings. But I won't say so much here, let's explore it slowly.

Guess you like

Origin blog.csdn.net/weixin_38322371/article/details/115197015