我正在使用 Android Studio 制作一个简单的应用程序来创建一些 PDF 文件来存储一些数据。我只想为用户自动打开生成的 PDF 做出一个意图。
这只是画布上绘制的文本并保存为下载的 PDF。工作正常
canvas.drawText(text ,x ,y, paint);
document.finishPage(page);
File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String fileName = "document.pdf";
File file = new File(downloadsDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
document.writeTo(fos);
document.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
showPdf();
这是我打开生成的文件的尝试
public void showPdf() {
try {
File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String fileName = "document.pdf";
File file = new File(downloadsDir, fileName);
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
应用程序运行良好,没有崩溃。但生成 PDF 后没有任何反应。
从Android 7.0开始,您不能使用Uri.fromFile()来共享文件URI。使用 FileProvider 获取内容 URI。
设置方法如下:
在应用程序标签下添加AndroidManifest.xml
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
在res/xml目录下创建XML文件file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="." />
</paths>
现在更新您的 showPdf 方法以使用 FileProvider
public void showPdf() {
try {
File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String fileName = "document.pdf";
File file = new File(downloadsDir, fileName);
Uri path = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".fileprovider", file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}}
确保设备上安装了 PDF 阅读器应用程序。如果没有可以处理应用程序/pdf 的应用程序,则意图将不会导致任何可见的操作。