How to download image/video file in Android R with help of MediaStore?

Viewed 700

As getExternalStoragePublicDirectory has been deprecated in Android Q and recommendation is to use MediaStore API

Here is my Image URL https://cdn.pixabay.com/photo/2020/04/21/06/41/bulldog-5071407_1280.jpg

I want to download this image file and want to save the shared folder i.e. Downloads or Pictures Folder as per MediaStore API

Below is the sample code

ContentResolver resolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);

Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues); 

Note: compileSdkVersion 30

I want an example of How to download an Image/Video file in Android R and save it into the download folder location with MediaStore.

2 Answers

Hi Kanaiya I answered an improvement on MediaStore answer MediaStore.Images.Media.insertImage deprecated

I did use workManager and viewModel not sure if that would apply to your use-case, I did test my answer on API 26 and on API 30.

My working sample is just a 2018 workmanager codelab for which I made minor changes to remove a depreciated api call, thanks for the original idea commonsware

In order to save it on android 10. Then after calling the insert method you will get the URI then call

os = getContentResolver().openOutputStream(uri);

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.close();

In Android 10 calling insert method is not enough

Your code will look like this

ContentResolver resolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);

Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues); 

OutputStream os = getContentResolver().openOutputStream(uri);

Bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.close();

Related