android11升级分区存储之后保存视频文件

忽然发现原来的测试程序中直接通过FileOutputStream获取FileDescriptor的代码不能用了:

            String date = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String name = "/sdcard/DCIM/Camera/VID_" + date + ".mp4";
            try {
                FileOutputStream out = new FileOutputStream(name);
                FileDescriptor fd = out.getFD();
                saveVideo(fd);
            } catch (IOException e) {
                e.printStackTrace();
            }

需要修改为通过MediaStore才能创建/sdcard/DCIM/Camera下的文件:


        String date = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String name = "VID_" + date + ".mp4";
        ContentValues values = new ContentValues();
        values.put(MediaStore.Video.Media.DISPLAY_NAME,  name);
        values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            values.put(MediaStore.Video.Media.RELATIVE_PATH, "DCIM/Camera");
        } else {
            values.put(MediaStore.Video.Media.DATA, "/sdcard/DCIM/Camera/" + name);
        }
        Uri videoUri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
        ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(videoUri, "rw", null);
        saveVideo(pfd.getFileDescriptor());

具体Android对于权限的升级可以参考:访问共享存储空间中的媒体文件

https://developer.android.google.cn/training/data-storage/shared/media

你可能感兴趣的:(android,media)