背景:
Android 7.0后直接把文件的Uri暴露给其它APP会抛出android.os.FileUriExposedException
异常,只能通过FileProvider
的方式向其它APP暴露文件。
具体步骤
1.在Manifest中声明provider
<manifest>
...
<application>
...
<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/<file_paths_name>" />
...
</application>
</manifest>
2.在res/xml
目录下创建<file_paths_name>.xml,替provider指明对外公开的目录。只有在该xml中引入的目录下的文件才能对外分享成功,如果一个文件不在声明的目录中,分享给外部APP的时候回抛出异常java.lang.IllegalArgumentException: Failed to find configured root that contains...
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="file" path="files/"/>
<files-path name="images" path="images/"/>
<external-path name="external_file" path="/"/>
</paths>
3.获取文件对外的uri
private Uri getUriForFile(File file) {
Uri uri = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(this, getPackageName() + ".provider", file);
} else {
uri = Uri.fromFile(file);
}
return uri;
}
4.安装apk
private void installApk() {
File dir = Environment.getExternalStorageDirectory();
File apkFile = new File(dir, "test.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(getUriForFile(apkFile), "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 这一行代码不要漏掉,否则外部还是无法读取到文件
startActivity(intent);
}
参考:
https://developer.android.com/reference/android/support/v4/content/FileProvider.html#Permissions