问题描述
myfile.exists() 返回 TRUE,但我无法打开 pdf:
File myfile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
+ File.separator + fileString ); //fileString=sample.pdf
Log.i("here",fileString + "---"+ myfile.exists());
pdfView = findViewById(R.id.pdfViewer);
pdfView.fromFile(myfile)
.defaultPage(0)
.spacing(2)
.load();
我在 android 中使用这个库进行 Pdf 视图。
implementation 'com.github.barteksc:android-pdf-viewer:3.2.0-beta.1'
如果你愿意,我可以发布所有可用的代码片段。
(使用 pdfView.fromUri() 工作正常,但只有一次。我的目标是从 Intent.ACTION_OPEN_DOCUMENT 中选择一个 .pdf 并保存它的 uri 以备下次使用。
解决方法
我使用了 pdfView.fromUri(),而不是 pdfView.fromFile(),
pdfView = findViewById(R.id.pdfViewer);
//pdfView.fromFile(myfile)
pdfView.fromUri(Uri.parse(getIntent_uri))
.defaultPage(0)
.spacing(2)
.load();
然后在选择文件后,在 onActivityResult() 中我使用 takePersistableUriPermission() 使 uri 永久可访问。
@Override
protected void onActivityResult(int requestCode,int resultCode,@Nullable @org.jetbrains.annotations.Nullable Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == PICK_PDF_FILE && resultCode == Activity.RESULT_OK && data != null) {
Uri uri = data.getData();
getContentResolver().takePersistableUriPermission(uri,Intent.FLAG_GRANT_READ_URI_PERMISSION);
特别感谢@CommonsWare