'getExternalStoragePublicDirectory deprecated warning persists below Android Q
Since Android 10, getExternalStoragePublicDirectory was deprecated in favor of other alternatives such as MediaStore or getExternalFilesDir.
I am saving videos to the "DCIM->MyFolder" directory.
- For Android 10 and above, I use
MediaStoreto get theFileDescriptor:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
FileDescriptor fileDescriptor;
Uri videoUri;
ContentResolver resolver = this.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/" + "MyFolder");
videoUri = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentValues);
ParcelFileDescriptor descriptor = this.getContentResolver().openFileDescriptor(videoUri, "w");
fileDescriptor = descriptor.getFileDescriptor();
return fileDescriptor;
}
Then open an OputputStream to be able to write the file:
outputStream = new FileOutputStream(fileDescriptor);
- For devices below Android 10, I use
Environment.getExternalStoragePublicDirectory:
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
String outputPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "MyFolder") + "/";
}
Then open the OutputStream: outputStream = new FileOutputStream(outputPath + fileName);
The problem: Despite targeting the right Android versions, Android Studio still gives me a warning about the deprecated getExternalStoragePublicDirectory method.
Question: What is the correct way to get the /storage/emulated/0/DCIM path without using deprecated methods?
Note:
- MediaStore cannot be used below API 29 because of this
MediaStore.MediaColumns.RELATIVE_PATH - I cannot use
getExternalFilesDirbecause it returns a path to the application internal storage and my saved videos wouldn't be visible in gallery.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
