Android7.0 FileUriExposedException / 调用其他应用错误
Android 7.0以上,为了安全,intent不允许直接带有file,要不然会抛出FileUriExposedException
以下是让第三方应用打开ppt文件案例:
一、在AndroidManifest.xml的 中添加provider标签:
这一步主要是设置共享数据的配置,大部分情况采用如下设置即可,全部直接copy即可,包名改下就行了。想要详细更改查看这里(记得挂vpn)
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="包名"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
踩坑:有些教程里在包名后面加上了.fileProvider,我这里遇到情况是加了.fileProvider以后FileProvider.getUriForFile会提示空指针。
二、在res下建一个file_paths.xml
在file_paths文件夹内声明的都是需要对外共享的目录。
这里重点说明一下paths内还可以声明很多种类型的标签,每一种标签都代表不同路径下。后面我有附上各种路径对应的标签
- 标签:external-path代表Environment.getExternalStorageDirectory() 获取的路径。我这里获取到都是"/storage/emulated/0/"
- name:随意写
- path:内容与标签组合,我这里也就是"/storage/emulated/0/ppts"
<external-path
name="sssss"
path="test/ssss"/>
哪我这里设置的共享路径就是:"/storage/emulated/0/test/ssss"
最后附上各种路径对应的标签:
files-path | getFilesDir() |
---|---|
cache-path | getCacheDir() |
external-path | Environment.getExternalStorageDirectory() |
external-files-path | Context#getExternalFilesDir(String) 或 Context.getExternalFilesDir(null) |
external-cache-path | Context.getExternalCacheDir() |
external-media-path | Context.getExternalMediaDirs() |
三、代码
...
//因为我设置了标签external-path与path="ppts"所有最终共享路径为"/storage/emulated/0/ppts/"
File file = new File("/storage/emulated/0/ppts/all.pptx");
openFile(this, file);
...
public void openFile(Context context, File file) {
try {
Intent intent = new Intent();
//这一步很重要。给目标应用一个临时的授权。
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//设置intent的Action属性
intent.setAction(Intent.ACTION_VIEW);
//获取文件file的MIME类型,这里不用管,根据你自己的文件类型进行设置就好,PPT:application/vnd.openxmlformats-officedocument.presentationml.presentation
String type = getMIMEType(file);
//设置intent的data和Type属性。
intent.setDataAndType(FileProvider.getUriForFile(this, "com.jj.app.zcfjclient", file), type);
//跳转
context.startActivity(intent);
// Intent.createChooser(intent, "请选择对应的软件打开该附件!");
} catch (ActivityNotFoundException e) {
// TODO: handle exception
Toast.makeText(context, "sorry附件不能打开,请下载相关软件!", Toast.LENGTH_SHORT).show();
}
}
参考文章:
https://blog.csdn.net/qq_29678299/article/details/51108342
https://www.cnblogs.com/kezhuang/p/8706988.html