首先不得不说的一点就是亲爱前一段时间碰到的问题
关于SDK24y以上的版本没有办法直接将file://通过uri的方式发送到其他应用程序上去,必须要用content://这种方式去发送内容,所以在更新安装包的时候我就遇到了FileUriException
我们就需要使用FileProvider
我们看一下使用的步骤
首先在AndroidMainfest.xml内进行注册
<provider android:name="android.support.v4.content.FileProvider" android:authorities="applicationId.fileprovider" android:grantUriPermissions="true"
android:exported="false">
<!--元数据-->
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/apk_file_paths" />
</provider>
说一下相关的参数
- android:authorities:该参数要使用包名.fileprovider
- android:grantUriPermissions=”true” 要给接受Uri的程序权限
- android:exported=”false” 这个参数必须要给false否则会报错
- android:resource=”@xml/apk_file_paths” 这个参数是元数据,可以引用res下面的xml文件,文件的名字是可以随便取的\
创建apk_file_paths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="download"
path="" />
</paths>
内部的参数分别对应着以下几种方法
- files-path—Context.getFilesDir()
- cache-path—-Context.getCacheDir()
- external-path—Environment.getExternalStorageDirectory()
- external-files-path—Context.getExternalFilesDir()
- external-cache-path—Context.getExternalCacheDir()
path给”“和”.”表示根目录,方法具体对应的文件具体的意思应该不用我解释了吧
代码的改动
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri apkUri=FileProvider.getUriForFile(context,context.getPackageName() + ".fileprovider", file);
intent.setDataAndType(apkUri,"application/vnd.android.package-archive");
} else {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
context.startActivity(intent);
差别就在与FileProvider.getUriForFile()这个方法Intent.FLAG_GRANT_READ_URI_PERMISSION这个flag主要的目的就是将file://转换为content://这样的形势
这个是安装apk包的写法,其他的大同小异
在这里记录一下
有不对的地方欢迎指正