mediastore.images.media.data android 10 code example
Example: How to create a video file path on Android 10
private fun saveMediaFile2(filePath: String?, isVideo: Boolean, fileName: String) {
filePath?.let {
val context = MyApp.applicationContext
val values = ContentValues().apply {
val folderName = if (isVideo) {
Environment.DIRECTORY_MOVIES
} else {
Environment.DIRECTORY_PICTURES
}
put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
put(MediaStore.Images.Media.MIME_TYPE, MimeUtils.guessMimeTypeFromExtension(getExtension(fileName)))
put(MediaStore.Images.Media.RELATIVE_PATH, folderName + "/${context.getString(R.string.app_name)}/")
put(MediaStore.Images.Media.IS_PENDING, 1)
}
val collection = if (isVideo) {
MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
} else {
MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
}
val fileUri = context.contentResolver.insert(collection, values)
fileUri?.let {
if (isVideo) {
context.contentResolver.openFileDescriptor(fileUri, "w").use { descriptor ->
descriptor?.let {
FileOutputStream(descriptor.fileDescriptor).use { out ->
val videoFile = File(filePath)
FileInputStream(videoFile).use { inputStream ->
val buf = ByteArray(8192)
while (true) {
val sz = inputStream.read(buf)
if (sz <= 0) break
out.write(buf, 0, sz)
}
}
}
}
}
} else {
context.contentResolver.openOutputStream(fileUri).use { out ->
val bmOptions = BitmapFactory.Options()
val bmp = BitmapFactory.decodeFile(filePath, bmOptions)
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out)
bmp.recycle()
}
}
values.clear()
values.put(if (isVideo) MediaStore.Video.Media.IS_PENDING else MediaStore.Images.Media.IS_PENDING, 0)
context.contentResolver.update(fileUri, values, null, null)
}
}
}