由于Android 7.0強(qiáng)制啟用了 StrictMode策略攻泼,禁止你的App對外暴露file://類型的URI火架。需要使用FileProvider解決。
新建一個(gè)file_paths.xml文件放在res的xml包下
<?xml version="1.0" encoding="utf-8"?>
<resources>
<paths>
<external-path
path=""
name="Download"/>
</paths>
</resources>
在AndroidManifest.xml配置
<!-- 適配7.0獲取uri -->
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
/**
* 安裝apk
*/
public void installApk(Context context) {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri;
if (SdkVersionUtils.hasNougat()) {
uri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider",
new File(DOWNLOAD_SAVE_PATH + File.separator + versionUpdateModel.getApp_name()));
} else {
uri = Uri.fromFile(new File(DOWNLOAD_SAVE_PATH + File.separator + versionUpdateModel.getApp_name()));
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
context.startActivity(intent);
}
部分手機(jī)在下載apk前還需要申請外部存儲(chǔ)卡權(quán)限
if (SdkVersionUtils.hasMarshmallow()) {//6.0
mRxPermissions
.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.subscribe(granted -> {
if (granted) {
//download
} else if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE))
ToastUtils.showShortToast(context, "已拒絕寫入外部存儲(chǔ)卡權(quán)限");
} else {
ToastUtils.showShortToast(context, "獲取外部存儲(chǔ)卡權(quán)限失敗忙菠,需去系統(tǒng)設(shè)置中打開");
}
});
} else {
//download
}