背景:
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
目錄下創(chuàng)建<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