Android8.0后需要使应用可以安装未知来源应用才可以安装更新包,做内部更新
设置res->xml->file_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path path="Android/data/此处填写applicationId(即包名)/" name="files_root" />
<external-path path="." name="external_storage_root" />
</paths>
AndroidManifest文件配置
<application>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="此处填写applicationId(即包名).fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<!-- 元数据 -->
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
新建工具类
public class InstallAppUtils {
public static void installApp(Context context , File updateFile) {
// 核心是下面几句代码
if (null != updateFile) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
//兼容7.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(context, "此处填写applicationId(即包名).fileprovider", updateFile);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
//兼容8.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
boolean hasInstallPermission = mActivity.getPackageManager().canRequestPackageInstalls();
if (!hasInstallPermission) {
ToastUtil.showLong("请在设置界面设置本应用允许安装应用");
startInstallPermissionSettingActivity(context);
return;
}
}
} else {
intent.setDataAndType(Uri.fromFile(updateFile), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
if (mActivity.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
mActivity.startActivity(intent);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
/**
* 跳转到设置-允许安装未知来源-页面
*/
@RequiresApi(api = Build.VERSION_CODES.O)
private static void startInstallPermissionSettingActivity(Context context) {
//注意这个是8.0新API
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mActivity.startActivity(intent);
}
}
调用
InstallAppUtils.installApp(context, updateApk)
网友评论