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)
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)
归档时间: |
|
查看次数: |
69094 次 |
最近记录: |