【Android 】android13 新权限获取 读写文件权限

android13 新权限获取
参考:Android 13(API 33)读写SD卡权限的调整适配 - Mr,Han - 博客园
android在 获取文件读写权限(尤其是音视频、图片等等资源)的权限获取逻辑更换了。
必须申请如下权限:
【Android 】android13 新权限获取 读写文件权限_第1张图片

   public static final String READ_MEDIA_AUDIO = "android.permission.READ_MEDIA_AUDIO";
   public static final String READ_MEDIA_IMAGES = "android.permission.READ_MEDIA_IMAGES";
   public static final String READ_MEDIA_VIDEO = "android.permission.READ_MEDIA_VIDEO";

这段逻辑可以看上面的文件拷贝类的代码:

  /**
     *  权限检查
     * @param context
     * @return
     */
    private boolean hasStoragePermissions(Context context) {
        //版本判断,如果比android 13 就走正常的权限获取
        if(android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU){
            int readPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
            int writePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            return readPermission == PackageManager.PERMISSION_GRANTED && writePermission == PackageManager.PERMISSION_GRANTED;
        }else{
            int audioPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_MEDIA_AUDIO);
            int imagePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_MEDIA_IMAGES);
            int videoPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_MEDIA_VIDEO);
            return audioPermission == PackageManager.PERMISSION_GRANTED && imagePermission == PackageManager.PERMISSION_GRANTED && videoPermission == PackageManager.PERMISSION_GRANTED;
        }
    }

    private void requestStoragePermissions(Context context) {
        String [] permissions;
        if(android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU){
            permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        }else{
            permissions = new String[]{Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES,Manifest.permission.READ_MEDIA_VIDEO};
        }
        ActivityCompat.requestPermissions((Activity) context,
                permissions,
                STORAGE_PERMISSION_REQUEST_CODE);
    }

你可能感兴趣的:(android代码小结,android)