在引入范围存储之前,我使用下载管理器在我的应用程序中下载 pdf 并从中获取 pdf getExternalStorageDirectory
,但由于范围存储,我不能再使用getExternalStorageDirectory
它,因为它已被弃用。我决定离开下载管理器,它在公共目录中下载文件,而是使用改造来下载 pdf 文件。我知道我可以requiredLegacyStorage
在 Android Manifest 中使用该标签,但它不适用于 Android 11,所以我没有使用它。
这是我的代码
fun readAndDownloadFile(context: Context) {
readQuraanInterface?.downloadFile()
Coroutines.io {
file = File(context.filesDir,"$DESTINATION_DIRECTORY/$FILE_NAME$FILE_EXTENSION")
if (file?.exists() == true) {
renderPDF()
showPdf(mPageIndex, Direction.None)
} else {
Log.i("new","new0")
val response = readQuraanRepository.downloadPdf()
if (response.isSuccessful) {
Log.i("new","new00 ${file!!.path} ${response.body()?.byteStream().toString()}")
response.body()?.byteStream()?.let {
file!!.copyInputStreamToFile(
it
)
}
Log.i("new","new1")
// renderPDF()
// showPdf(mPageIndex, Direction.None)
} else {
Log.i("new","new2")
Coroutines.main {
response.errorBody()?.string()
?.let { readQuraanInterface?.downloadFailed(it) }
}
}
}
}
}
private fun File.copyInputStreamToFile(inputStream: InputStream) {
this.outputStream().use { fileOut ->
Log.i("new","new30")
inputStream.copyTo(fileOut)
}
}
虽然下载了 pdf id,但该文件从未使用我编写的 InputStream 辅助函数存储。我需要将该 pdf 添加到我的应用程序的内部存储中,并使用 PDFRenderer 渲染它。