[英]Unable to open PDF file through intent programmatically in android
我有一个应用程序,点击按钮,应该提供访问权限以浏览和打开存储在设备内部存储器中的 PDF 文件。我尝试了各种代码,但我祝酒词说“无法显示 PDF”。 我在日志中没有收到任何错误。 我使用 android 版本 7.0 设备。 下面附上我的代码:请帮助:
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);
我已将此包含在 Oncreate 中:
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
这就是调用方法的方式:
linear_pdf.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pdf.setTextColor(getActivity().getResources().getColor(R.color.colorWhite));
openPdf(getContext(), Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
communication.dismiss();
}
});
试试这个...
public void openPdf(Context context, String path){
File file = new File(path);
if (file.exists()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
PackageManager pm = context.getPackageManager();
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setType("application/pdf");
Intent openInChooser = Intent.createChooser(intent, "Choose");
List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
if (resInfo.size() > 0) {
try {
context.startActivity(openInChooser);
} catch (Throwable throwable) {
Toast.makeText(context, "PDF apps are not installed", Toast.LENGTH_SHORT).show();
// PDF apps are not installed
}
} else {
Toast.makeText(context, "PDF apps are not installed", Toast.LENGTH_SHORT).show();
}
}
}
调用此方法:
openPdf(getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
打开一个特定文件:
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/your_directory/" + "your_file_name" + ".pdf");
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(getContext(), "No required app", Toast.LENGTH_SHORT).show();
}
检查目录,这个有效。
要从本地存储打开 pdf 文件,请在 url 中添加前缀。
private void openPdf(File file) {
try {
String url = file.getAbsolutePath();
String u = "file:///" + url;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(u));
startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.