官方解释
意思大概是:app内可以使用file://这种形式,7.0以后跨应用只能使用content://这种形式,并且要声明权限.
注意并不仅仅是安装app需要这样,想相册、拍照跨应用的文件共享都需要这样
解决实例:
在AndroidManifest.xml中application节点里面添加provider节点中的代码
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
说明:
authorities:app的包名.fileProvider (fileProvider可以随便写),上面采用的是gradle的替换直接写成包名也可以,但是推荐这种方式,多渠道分包的时候不用关心了
grantUriPermissions:必须是true,表示授予 URI 临时访问权限
exported:必须是false
resource:中的@xml/file_paths是我们接下来要添加的文件
2、在res目录下新建一个xml文件夹,并且新建一个provider_paths的xml文件
说明:
文件名随意写,跟第一步中resource中定义的一样即可,
3、打开provider_paths.xml文件添加如下内容
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
说明:
external-path中,
name:可以随意写,只是一个名字
path:表示文件路径,. 表示所有paths下可以有一下节点
<external-cache-path name="name" path="path" />对应Context.getExternalCacheDir()得到的目录
<external-files-path name="name" path="path" />对应Context#getExternalFilesDir(String) Context.getExternalFilesDir(null)
<external-path name="name" path="path" /> 对应Environment.getExternalStorageDirectory()
<cache-path name="name" path="path" />对应 getCacheDir()得到的目录
<files-path name="name" path="path" />对应Context.getFilesDir() 目录
4、修改安装对应的代码
//7.0对隐私权限进行了修改 app内如使用的uri不能用intent提供给外部使用 否则会报异常
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
intent.setDataAndType(Uri.fromFile(new File(BASE_PATH)), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
} else {
// 声明需要的临时权限
// 第二个参数,即第一步中配置的authorities
Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", new File(BASE_PATH));
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
}
startActivity(intent);
说明:
低于7.0的版本还使用老的方式,而高于的要用新的获取uri的方式。
其中authorities使用的是BuildeConfig获取的包名,也可以自己写全,但是推荐使用这种方式,万一改了包名也不用关心了。
BASE_PATH是自己的文件路径.