将打开的文件复制到应用程序目录中以备将来使用



所以我有一个android应用程序,它可以打开并显示PDF,我让用户选择像这样的PDF

fun openFile() {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "application/pdf"
putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("application/pdf"))
putExtra(DocumentsContract.EXTRA_INITIAL_URI, MediaStore.Files.getContentUri("external"))
}
activity?.startActivityForResult(intent, REQUEST_CODE_PDF_FILE)
}

然后我从活动结果中检索URI,显示它并保存URI。然而,下次打开应用程序时,我想打开同一个文件,现在当我尝试打开保存的URI时,我会得到以下信息:

ava.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{c3dfcb2 32587:ca.thing.testapp/u0a237} (pid=32587, uid=10237) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
at android.os.Parcel.createExceptionOrNull(Parcel.java:2425)
at android.os.Parcel.createException(Parcel.java:2409)
at android.os.Parcel.readException(Parcel.java:2392)
at android.os.Parcel.readException(Parcel.java:2334)
at android.app.IActivityManager$Stub$Proxy.getContentProvider(IActivityManager.java:5850)
at android.app.ActivityThread.acquireProvider(ActivityThread.java:6973)

很明显,在关闭并重新打开应用程序后,我不再有使用所选文件的权限。所以我想我需要做的是将该文件复制到我有权限的某个缓存目录中,这样我就可以在应用程序重新打开时显示它。我该怎么做呢?

您应该在onActivityResult中获得持久的uri权限,以便以后使用该uri。

不需要复印。

相关内容

最新更新