android - 如何使用 Storage Access Framework android 将文件保存到下载文件夹?
问题描述
我正在从服务器下载文件,并保存到android中的下载文件夹,通过以下方式访问文件路径以保存
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
在 Android Q 中已弃用,所以我必须使用存储访问框架。
fun downloadFile(url: String, originalFileName: String) {
mDownloadDisposable.add(
mRCloudRepository.downloadFile(url)
.flatMap(object : Function1<Response<ResponseBody>, Flowable<File>> {
override fun invoke(p1: Response<ResponseBody>): Flowable<File> {
return Flowable.create({
try {
val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absoluteFile, originalFileName)
val sink = file.sink().buffer()
sink.writeAll(p1.body()!!.source())
sink.close()
it.onNext(file)
it.onComplete()
} catch (e: IOException) {
e.printStackTrace()
it.onError(e)
}
}, BackpressureStrategy.BUFFER)
}
})
.subscribeOn(mIoScheduler)
.observeOn(mUiScheduler)
.subscribe(
{
cancelNotification()
val contentIntent: PendingIntent = PendingIntent.getActivity(mContext, NotificationBuilder.NOTIFICATION_DOWNLOAD_ID, getOpenFileIntent(it), PendingIntent.FLAG_CANCEL_CURRENT)
NotificationBuilder.showDownloadedNotification(mContext!!, 2, "Downloaded $originalFileName ", "", contentIntent)
}, {
cancelNotification()
it.printStackTrace()
}
)
)
}
解决方案
DocumentFileCompat#createDownloadWithMediaStoreFallback()
您可以在Simple Storage中尝试:
val uri = DocumentFileCompat.createDownloadWithMediaStoreFallback(applicationContext, FileDescription(filename))
val output = uri?.openOutputStream(applicationContext)
val input = // get input stream from Response<ResponseBody>
// then, write input stream to output stream
在 Android 10 中,访问目录中的Download
文件需要 URI,而不是直接的文件路径。
推荐阅读
- python - Snakemake 创建通配符
- javascript - jQuery、ready(function() 和 .click(function() 使用相同的代码执行不同的操作
- linux - 如何使用 grep 命令将 docker 日志重定向到文本文件?
- linux - 我在 azure linux VM 上有两个磁盘,sda 和 sdb
- python - 如何在 RHEL 上安装 libnfs 模块?
- java - 在某些情况下我应该如何使用模拟?
- figma - 如何使用 figma rest api 将元素导出为 PNG 或 JPEG?
- java - 使用一个默认值Guice 多个连接
- javascript - 检查递归js中的数字是否不是整数
- python - Python在正文中缺少数据