1、检查更新接口,获取最新app版本以及下载链接
2、下载apk文件到Context.getCacheDir() app缓存目录下,方便清理
3、安装apk
3.1、配置安装apk的权限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
3.2、在AndroidManifest的application中配置provider和meta-data
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.zjw.touchscreen.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
3.1、实现安装代码
protected void installApk(File file) {
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= 24) {
//注意getUriForFile的第二个参数和AndroidManifest中配置的android:authorities保持一致
Uri apkUri = FileProvider.getUriForFile(this,"com.zjw.touchscreen.fileProvider", file);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
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");
}
this.startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
}