簡體   English   中英

如何使用 Storage Access Framework android 將文件保存到下載文件夾?

[英]How to Save files to download folder using 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()
                    }
                    )
    )
}

您可以在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,而不是直接文件路徑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM