如何使用Storage Access Framework Android将文件保存到下载文件夹?

时间:2019-12-18 11:03:14

标签: android kotlin android-10.0 storage-access-framework

我正在从服务器下载文件,并保存到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()
                    }
                    )
    )
}

1 个答案:

答案 0 :(得分:0)

您可以在Simple Storage中尝试DocumentFileCompat#createDownloadWithMediaStoreFallback()

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,而不是直接文件路径。