I'm trying to support scoped storage and trying to unify the implementation for dealing with the media files: inserting media files to mediaStore done successfully but with arbitrary name for ex: if the file name was geeks.jpg
it actually creates it as ex 599345665432.jpg
fun writeImage(inputStream: InputStream, fileName: String): Uri? {
val collectionUri = if (atLeastQ()) {
MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
} else {
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
}
val imageDetails = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
put(MediaStore.Images.Media.TITLE, fileName)
if (atLeastQ()) put(MediaStore.Images.Media.IS_PENDING, 1)
}
val imageContentUri = contentResolver.insert(imageCollection, imageDetails)
imageContentUri?.let {
contentResolver.openOutputStream(it)?.use { outputImageFile ->
inputStream.writeFully(outputImageFile)
}
if(atLeastQ()) {
imageDetails.clear()
imageDetails.put(MediaStore.Images.Media.IS_PENDING, 0)
contentResolver.update(imageContentUri, imageDetails, null, null)
}
}
return imageContentUri
}
private fun atLeastQ() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
This code works fine for me, but it works only for pictures:
public void saveFileToPhone(InputStream inputStream, String filename) {
OutputStream outputStream;
Context myContext = requireContext();
try {
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.Q){
ContentResolver contentResolver = requireContext().getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Downloads.DISPLAY_NAME,filename);
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
Uri collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
Uri fileUri = contentResolver.insert(collection, contentValues);
outputStream = contentResolver.openOutputStream(Objects.requireNonNull(fileUri));
Objects.requireNonNull(outputStream);
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I would suggest using SimpleStorage because it will be simpler:
val desc = FileDescription("geeks", "", "image/jpeg")
val media = MediaStoreCompat.createImage(this, desc, ImageMediaDirectory.PICTURES)
media?.openOutputStream()?.use { outputStream ->
inputStream.writeFully(outputStream)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.