安卓Q更新
这是一个较旧的问题,但在 Android Q 中,由于新的文件访问权限/系统,出现了一些变化。现在不可能再将 PDF 文件存储在公共文件夹中。我通过在中创建 PDF 文件的副本解决了这个问题cache
我的应用程序的数据/数据文件夹中。通过这种方法的许可WRITE_EXTERNAL_STORAGE
不再需要。
打开 PDF 文件:
fun openPdf(){
// Open the PDF file from raw folder
val inputStream = resources.openRawResource(R.raw.mypdf)
// Copy the file to the cache folder
inputStream.use { inputStream ->
val file = File(cacheDir, "mypdf.pdf")
FileOutputStream(file).use { output ->
val buffer = ByteArray(4 * 1024) // or other buffer size
var read: Int
while (inputStream.read(buffer).also { read = it } != -1) {
output.write(buffer, 0, read)
}
output.flush()
}
}
val cacheFile = File(cacheDir, "mypdf.pdf")
// Get the URI of the cache file from the FileProvider
val uri = FileProvider.getUriForFile(this, "$packageName.provider", cacheFile)
if (uri != null) {
// Create an intent to open the PDF in a third party app
val pdfViewIntent = Intent(Intent.ACTION_VIEW)
pdfViewIntent.data = uri
pdfViewIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(Intent.createChooser(pdfViewIntent, "Choos PDF viewer"))
}
}
内部提供者配置provider_paths.xml
用于在您自己的应用程序之外访问该文件。这允许访问该目录中的所有文件cache
folder:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path
name="cache-files"
path="/" />
</paths>
在您的文件中添加文件提供程序配置AndroidManifest.xml
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
可以通过仅复制文件一次并检查文件是否已存在并替换它来增强此功能。由于打开 PDF 并不是我的应用程序的重要组成部分,因此我只是将其保存在缓存文件夹中,并在用户每次打开 PDF 时覆盖它。