现象:在适配Android11迁移文件夹时,遇到一个问题。在Android11以下版本迁移多媒体文件成功后,我们使用SAF选择文件时,还是可以看到多媒体文件。但是多媒体文件已经不存在了。
原因:虽然我们的多媒体文件已经不存在了,但是MediaStore
中的数据库还存在原来多媒体文件的数据。
解决方案:那我们刷新一下MediaStore
中的数据库就可以了。可以通过MediaScannerConnection.scanFile
静态方法来刷新。我这里封装了一下,传入目录或者文件都可行。我这里没有传如mimeType是因为文件夹下的多媒体内容不确定,所以就没有把mimeType作为参数。如果文件夹下只有一种格式多媒体,可以多加一个mimeType参数。
class MediaScannerUtils private constructor() {
companion object {
@JvmStatic
@WorkerThread
fun scanFile(context:Context, paths: List<String>) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
return
}
val filterPaths = ArrayList<String>()
for (path in paths) {
if (TextUtils.isEmpty(path)) {
continue
}
val file = File(path)
if (!file.exists()) {
val parentFile = file.parentFile ?: continue
filterPaths.add(parentFile.absolutePath)
}
filterPaths.add(path)
}
if (filterPaths.isEmpty()) {
return
}
val countDownLatch = CountDownLatch(filterPaths.size)
MediaScannerConnection.scanFile(context, paths.toTypedArray(), null) { path, uri ->
countDownLatch.countDown()
Log.e("wfeii", "onScanCompleted$uri")
}
try {
countDownLatch.await()
} catch (e: java.lang.InterruptedException) {
e.printStackTrace()
}
}
}
}
限于个人水平,有错误请指出,大家共同学习进步!
扫码关注公众号,查看更多内容。