android - 无法为intent android打开pdf文件
问题描述
我彻底检查了 pdf 文件是否存在,
/storage/emulated/0/Download/Abcd.pdf"
但无法有意打开它。
我在各种查看器中打开它,有些哦,它们导致错误:“无法打开文件”。微软的话说:check file in the device
,但是Abcd.pdf
当我在android文件系统的文件目录中打开文件时,文件打开得很好。
我是不是把路线设置错了?
AndroidManifest.xml
<provider
android:authorities="${applicationId}.provider"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
MainActivity.Java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent=new Intent();
File mypath=new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/","Abcd.pdf");
Log.e("download",mypath.getAbsolutePath());
//this log says : /storage/emulated/0/Download/Abcd.pdf
Uri pdfUri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".provider", mypath);
Log.e("download",mypath.exists()+"");
if (mypath.exists()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Log.e("download","result : "+pdfUri.getPath());
intent = new Intent(Intent.ACTION_VIEW);
intent.setType("application/pdf");
intent.putExtra(MediaStore.EXTRA_OUTPUT, pdfUri);
}else{
}
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Log.e("error","error"+e);
}
}
}
res/xml/provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="storage/emulated/0"
path="."/>
</paths>
解决方案
我正在使用这个功能:
public void openPdf(LocalFile magazine) {
if (BuildConfig.DEBUG)
Log.d(TAG, "openPdf() called with: magazine = [" + magazine + "]");
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
File file = new File(Uri.parse(magazine.getPath()).getPath());
Uri uri = FileProvider.getUriForFile(getContext(),
getContext().getApplicationContext().getPackageName() + ".provider", file);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
intent.setDataAndType(Uri.parse(magazine.getPath()), "application/pdf");
}
try {
startActivity(intent);
} catch (Throwable t) {
t.printStackTrace();
//attemptInstallViewer();
}
}
这对我来说很好。
推荐阅读
- codenameone - 代号未将构建发送到服务器
- reactjs - create-react-app + typescript 不使用 browserslist
- javascript - 获取新数据后刷新Leaflet Js并将其添加到标记中
- matplotlib - 将 plt.contour 转换为 np.array(等高线图形值转换为 np.array)
- r - R. 使用调查、样条和仅一个自变量值的错误预测
- reactjs - 使用 React 状态更改 antd 库中按钮的加载状态
- javascript - 如何更改按钮onclick jQuery的当前背景颜色
- django - 如何将字段值从一个模型对象传递到另一个模型对象?
- python - 监视 nodemon js 或 npm 中的新文件创建事件
- c# - 如何限制我的玩家在 Unity 中重生的次数?