如何通过SD卡从Intent打开PDF

Mik*_*e T 48 pdf android android-intent

我正在尝试启动一个Intent在我的应用程序中的资产文件夹中打开一个pdf.我已经阅读了几十篇帖子,但仍然被卡住了.显然我需要先将pdf复制到SD卡然后启动Intent.它仍然无法正常工作.

我认为问题是Intent启动所以我只是试图打开一个文件"example.pdf",我使用这段代码将其复制到SD卡上:

Log.w("IR", "TRYING TO RENDER: " + Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf"), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

try {
    startActivity(intent);
    Log.e("IR", "No exception");
} 
catch (ActivityNotFoundException e) {
    Log.e("IR", "error: " + e.getMessage());
    Toast.makeText(InvestorRelations.this, 
        "No Application Available to View PDF", 
        Toast.LENGTH_SHORT).show();
}
Run Code Online (Sandbox Code Playgroud)

这是我的LogCat输出.

05-10 10:35:10.950: W/IR(4508): TRYING TO RENDER: /mnt/sdcard/example.pdf
05-10 10:35:10.960: E/IR(4508): No exception
Run Code Online (Sandbox Code Playgroud)

除了运行此代码之外,我得到以下Toast(不是我的应用程序生成的)

"不支持的文档类型"

但我可以通过安装的PDF查看应用程序手动打开文档.任何帮助将非常感激.

use*_*305 120

试试这段代码,从/ sdcard显示pdf文件

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

  • 有关FLAG_ACTIVITY_NO_HISTORY的信息,请访问:https://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NO_HISTORY (3认同)
  • `Uri.fromFile(file)`在android N中不起作用. (3认同)
  • 谢谢你结束我的搜索.为什么它可以工作而不是从String解析url? (2认同)

Kap*_*put 11

对于Android Nougat及以上版本的android,还有一些工作要做,否则app将无法打开.pdf文件.我们必须设置临时URI使用权限FileProvider

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
   File file=new File(mFilePath);
   Uri uri = FileProvider.getUriForFile(this, getPackageName() + ".provider", file);
   intent = new Intent(Intent.ACTION_VIEW);
   intent.setData(uri);
   intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
   startActivity(intent);
   } else {
   intent = new Intent(Intent.ACTION_VIEW);
   intent.setDataAndType(Uri.parse(mFilePath), "application/pdf");
   intent = Intent.createChooser(intent, "Open File");
   intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(intent);
   }
Run Code Online (Sandbox Code Playgroud)