Lets say I\'m developing a chat app that is able to share with others ANY kind of files (no mimetype restriction): like images, videos, documents, but also compressed files like
I thought that it would best be to write the answer in java, as a lot of legacy code exists out there which would have to be updated. Also I have no idea what kind of file you want to store and so, here, I took an example of a bitmap. If you want to save any other kind of file you just have to create an OutputStream of it, and for the remaining part of it you can follow the code I write below. Now, here, this function is only going to handle the saving for Android 10+ and hence the annotation. I hope you have the prerequisite knowledge on how to save files in lower android versions
@RequiresApi(api = Build.VERSION_CODES.Q)
public void saveBitmapToDownloads(Bitmap bitmap) {
ContentValues contentValues = new ContentValues();
// Enter the name of the file here. Note the extension isn't necessary
contentValues.put(MediaStore.Downloads.DISPLAY_NAME, "Test.jpg");
// Here we define the file type. Do check the MIME_TYPE for your file. For jpegs it is "image/jpeg"
contentValues.put(MediaStore.Downloads.MIME_TYPE, "image/jpeg");
contentValues.put(MediaStore.Downloads.IS_PENDING, true);
Uri uri = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
Uri itemUri = getContentResolver().insert(uri, contentValues);
if (itemUri != null) {
try {
OutputStream outputStream = getContentResolver().openOutputStream(itemUri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
contentValues.put(MediaStore.Images.Media.IS_PENDING, false);
getContentResolver().update(itemUri, contentValues, null, null);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now if you want to create a sub directory i.e. a folder inside the Downloads folder you could add this to contentValues
contentValues.put(MediaStore.Downloads.RELATIVE_PATH, "Download/" + "Folder Name");
This will create a folder named "Folder Name" and store "Test.jpg" inside that folder.
Also do note this doesn't require any permissions in the manifest which implies it doesn't need runtime permissions as well. If you want the Kotlin version do ask me in the comments. I would happily and readily provide the Kotlin method for the same.