MediaStore.ACTION_VIDEO_CAPTURE URI to external storage

302 Views Asked by At

I am using an Intent to capture videos in my app. My code is similar to this (adapted from https://developer.android.com/training/camera-deprecated/photobasics):

File mVideo;

private File createVideoFile() throws IOException {
    @SuppressLint("SimpleDateFormat")
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmssSSS").format(new Date());
    String videoFileName = "VID_" + timeStamp + ".mp4";
    File storageDir = Environment.getExternalStorageDirectory();
    File movies = new File(storageDir, "Movies");
    if (!movies.exists() && !movies.mkdir()) {                 // suprisingly even this works?!
        Log.e(TAG, "could not create Movies directory");
        throw new IOException();
    }
    mCurrentVideo = new File(movies, videoFileName);
}

private final ActivityResultLauncher<Uri> requestRecordVideoLauncher =
        registerForActivityResult(new ActivityResultContracts.CaptureVideo(), success -> {
            if (success) {
                Log.i(TAG, "successfully recorded video")
                assert(mVideo.canRead());
            } else {
                if (!mCurrentVideo.delete()) {
                    Log.w(TAG, "could not delete aborted video recording");
                }
            }
        });

public void dispatchTakeVideoIntent() {
    File videoFile;
    try {
        createVideoFile();
    } catch (IOException ex) {
        Log.i(TAG, "could not create file")
        return;
    }
    Uri videoUri = FileProvider.getUriForFile(mContext, getPackageName() + ".provider", videoFile);
    requestRecordVideoLauncher.launch(videoUri);
}

I have a file provider registered with this path:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="."/>
</paths>

The major difference to the code in the developer manual is that I am using a path to public external storage. Thus, videos would usually be saved to the path /storage/emulated/0/Movies/VID_{DATE}{TIME}. Testing on different devices and emulators with different API levels (21, 30, 33) concludes that this is a legal thing to do (it does not even need any permissions to read the generated files).

From what I have read in the developer references, with scoped storage an app can still access all media files it has previously created without requesting any permission (https://developer.android.com/training/data-storage/shared/media#storage-permission-not-always-needed). Additionally, the File API can still be used to access files in external storage (https://developer.android.com/about/versions/11/privacy/storage#media-direct-file-native).

Do you think, it is a good idea to trust that this will still work in later Android versions? Is there any other way to easily record a video to external storage?

0

There are 0 best solutions below