[英]App Crashing on Android 9 while inserting media file
Media Insertion Code:媒体插入代码:
fun saveVideoToExternalStorage(
contentResolver: ContentResolver,
displayName: String,
file: File
): Uri {
val videoCollection = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
else MediaStore.Video.Media.EXTERNAL_CONTENT_URI
val contentValues = ContentValues().apply {
put(MediaStore.Video.Media.TITLE, displayName)
put(MediaStore.Video.Media.MIME_TYPE, "video/mp4")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(MediaStore.Video.Media.DISPLAY_NAME, displayName)
put(
MediaStore.Video.Media.RELATIVE_PATH,
"${Environment.DIRECTORY_MOVIES}/Coutloot"
)
} else {
var videosDir =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).path
videosDir += "/Coutloot"
with(File(videosDir, displayName)) {
put(MediaStore.Video.Media.DATA, path)
parentFile?.let {
if (!it.exists()) {
it.mkdir()
}
}
}
}
}
return try {
val uri = contentResolver.insert(videoCollection, contentValues)?.also { uri ->
contentResolver.openOutputStream(uri).use { outputStream ->
outputStream?.write(file.readBytes())
}
} ?: throw IOException("Couldn't create MediaStore entry")
uri
} catch (e: IOException) {
e.printStackTrace()
Uri.EMPTY
}
}
While saving app crashes on contentResolver.insert在contentResolver.insert上保存应用程序崩溃时
Here's the crash log这是崩溃日志
2021-11-17 18:43:00.979 785-785/company.coutloot W/System.err: java.lang.SecurityException: Permission Denial: writing com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=785, uid=10533 requires android.permission.WRITE_EXTERNAL_STORAGE, or grantUriPermission()
I tried adding running time permission too, but it did not work and this is only happening in Android 9. Can anyone suggest me how to fix this?我也尝试添加运行时权限,但它不起作用,这只发生在 Android 9 中。谁能建议我如何解决这个问题?
Try this code it works for me试试这个对我有用的代码
var fileOutputStream : OutputStream?
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
contentResolver.also { resolver ->
val contentValues = ContentValues().apply {
put(MediaStore.Video.Media.DISPLAY_NAME,displayName)
put(MediaStore.Video.Media.MIME_TYPE,"video/mp4")
put(MediaStore.Video.Media.RELATIVE_PATH,"${Environment.DIRECTORY_MOVIES}/Coutloot")
}
val videoUri = resolver.insert(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,contentValues
)
fileOutputStream = videoUri?.let {
resolver.openOutputStream(it)
}
}
}else{
val absolutePath =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath
val path = absolutePath.substring(0, absolutePath.length - 5) + "/Coutloot/"
val filePath = File(path)
if (!filePath.exists())
filePath.mkdir()
fileOutputStream = FileOutputStream(
File(filePath, displayName)
)
}
fileOutputStream?.write(file.readBytes())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.