添加依赖:
implementation 'com.github.LuoGuoXin:BaseAndroid:1.0.5'//版本更新
在project—build.gradle下配置
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
添加下载apk权限及注册内容提供者(安装APK在Android7.0后需要用到)
android:name="android.support.v4.content.FileProvider"
android:authorities="com.everywhere.trip"
android:exported="false"
android:grantUriPermissions="true">
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_path" />
向服务器获取版本号之后
VersionName版本检测
UpdateManager instance = UpdateManager.getInstance();
info = versionInfo.getResult().getInfo();
if (instance.updateApp(instance.getVersionName(this), info.getVersion())){
int type = 0;
if(luo.library.base.utils.UpdateManager.getInstance().isWifi(this)) {
type = 1;
}
if(false) {
type = 2;
}
String downLoadPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/downloads/";
File dir = new File(downLoadPath);
if(!dir.exists()) {
dir.mkdir();
}
//getDownload_url()为接口中的下载路径
fileName = info.getDownload_url().substring(info.getDownload_url().lastIndexOf("/") + 1, info.getDownload_url().length());
if(fileName == null && TextUtils.isEmpty(fileName) && !fileName.contains(".apk")) {
fileName = this.getPackageName() + ".apk";
}
File file = new File(downLoadPath + fileName);
UpdateManager.getInstance().setType(type).setUrl(info.getDownload_url()).setUpdateMessage("更新了UI\n添加图片缩放功能").setFileName(fileName).setIsDownload(file.exists());
if(type == 1 && !file.exists()) {
UpdateManager.getInstance().downloadFile(this);
} else {
UpdateManager.getInstance().showDialog(this);
}
}
VersionCode版本检测
BaseAndroid.checkUpdate(MainActivity.this, 2, downloadUrl,"更新了XXX\n修复OOO", false);
下面进行代码分析哈:首先是主方法
/**
* 版本更新
*
* @param context
* @param versionCode 版本号
* @param url apk下载地址
* @param updateMessage 更新内容
* @param isForced 是否强制更新
*/
public static void checkUpdate(Context context, int versionCode, String url, String updateMessage, boolean isForced) {
if (versionCode > UpdateManager.getInstance().getVersionCode(context)) {
int type = 0;//更新方式,0:引导更新,1:安装更新,2:强制更新
if (UpdateManager.getInstance().isWifi(context)) {
type = 1;
}
if (isForced) {
type = 2;
}
//检测是否已下载
String downLoadPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/downloads/";
File dir = new File(downLoadPath);
if (!dir.exists()) {
dir.mkdir();
}
String fileName = url.substring(url.lastIndexOf("/") + 1, url.length());
if (fileName == null && TextUtils.isEmpty(fileName) && !fileName.contains(".apk")) {
fileName = context.getPackageName() + ".apk";
}
File file = new File(downLoadPath + fileName);
//设置参数
UpdateManager.getInstance().setType(type).setUrl(url).setUpdateMessage(updateMessage).setFileName(fileName).setIsDownload(file.exists());
if (type == 1 && !file.exists()) {
UpdateManager.getInstance().downloadFile(context);
} else {
UpdateManage