Android加载assets下PDF打开后显示空白无内容问题求助
问题排查
核心错误点
- 文件名不匹配:你将assets里的
abc.pdf复制到应用私有目录后命名为abc.pdf,但跳转Intent里指定的文件名为sample.pdf,第三方PDF阅读器打开的是不存在的空文件,自然显示空白。 - Uri构造方式错误:你已经配置了FileProvider,不能手动拼接
content://格式的Uri,手动拼接的路径不符合FileProvider的路径映射规则,第三方应用无法正确读取文件内容。 - 使用了废弃的文件权限:
Context.MODE_WORLD_READABLE在Android 7.0及以上版本已经被官方废弃,该配置不会生效,且和FileProvider的授权逻辑冲突。 - (可选检查项)确认
res/xml/provider_paths.xml是否配置了正确的路径映射,需要包含files目录的规则:
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <files-path name="internal_files" path="." /> </paths>
修正后的代码
private void CopyReadAssets() { AssetManager assetManager = getAssets(); InputStream in = null; OutputStream out = null; // 统一文件名避免不匹配 String pdfFileName = "abc.pdf"; File file = new File(getFilesDir(), pdfFileName); try { in = assetManager.open("abc.pdf"); // 用MODE_PRIVATE替代废弃的MODE_WORLD_READABLE out = openFileOutput(file.getName(), Context.MODE_PRIVATE); copyFile(in, out); in.close(); out.flush(); out.close(); } catch (Exception e) { Log.e("tag", e.getMessage()); } Intent intent = new Intent(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); // 通过FileProvider生成符合规范的Uri Uri pdfUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file); intent.setDataAndType(pdfUri, "application/pdf"); startActivity(intent); } private void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } }
内容的提问来源于stack exchange,提问作者Amrita Thakur
相关产品推荐
相关产品推荐

