目前的项目之中基本上都会存在版本更新的功能,分为强制更新和推荐更新,其实功能点都是一样的,推荐更新只是增加一个按钮让更新的弹框隐藏掉而已,这里仅记录强制更新的功能
首先需要跟接口约定,需要判断是否弹出更新弹框
val isUpdate = VersionUtils.compareVersions("服务端新的版本号","本地版本号")
if (result.isIsNew && isUpdate) {
//检查更新
val checkVersionUtils = CheckVersionUtils(this, result.versionPath
, result.versionDesc, result.newVersion)
checkVersionUtils.showUpdateVersion()
}
这里的isNew为true表示有新版本更新,为false则没有更新,为了防止服务端出错,这里加上了本地的版本号和服务端的版本号进行匹配的字段
CheckVersionUtils
public class CheckVersionUtils {
private Context mContext;
private Dialog mDialog;
private TextView tvUpdate, tvProgress;
private ProgressBar progressBar;
private Logger logger = LoggerFactory.getLogger(CheckVersionUtils.class);
//下载地址
private String apkUrl;
private List apkDes;
private String newVersion;
public CheckVersionUtils(Context context, String apkUrl, List apkDes, String newVersion) {
this.mContext = context;
this.apkUrl = apkUrl;
this.apkDes = apkDes;
this.newVersion = newVersion;
}
/**
* 版本更新弹框
*/
@SuppressLint("SetTextI18n")
public void showUpdateVersion() {
mDialog = new Dialog(mContext, R.style.Teldialog);
mDialog.setContentView(R.layout.dialog_update_version);
mDialog.setCanceledOnTouchOutside(false);
mDialog.setCancelable(false);
mDialog.show();
tvUpdate = mDialog.findViewById(R.id.tv_update);
tvProgress = mDialog.findViewById(R.id.tv_progress);
progressBar = mDialog.findViewById(R.id.progress_bar);
TextView tvVersion = mDialog.findViewById(R.id.tv_version);
tvVersion.setText("v" + newVersion);
TextView tvDes = mDialog.findViewById(R.id.tv_des);
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < apkDes.size(); i++) {
String des = "· " + apkDes.get(i) + "\n";
stringBuffer.append(des);
}
tvDes.setText(stringBuffer);
//立即更新
tvUpdate.setOnClickListener(view -> {
tvUpdate.setVisibility(View.GONE);
tvProgress.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
initDownload();
});
}
/**
* 下载apk
*/
private void initDownload() {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
Request request = new Request.Builder()
.url(apkUrl)
.get()
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
logger.error("apk下载失败:" + e.getMessage());
apkUrl = apkUrl.replace("https", "http");
initDownload();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
InputStream inputStream = body.byteStream();
saveFile(inputStream, Environment.getExternalStorageDirectory() + "/" + "demo.apk", body.contentLength());
}
});
}
/**
* @param saveFile 存放的地址
* @param fileLength 文件的长度
*/
@SuppressLint("SetTextI18n")
private void saveFile(InputStream inputStream, String saveFile, final long fileLength) {
long count = 0;
try {
FileOutputStream outputStream = new FileOutputStream(new File(saveFile));
int length = -1;
byte[] bytes = new byte[1024 * 10];
while ((length = inputStream.read(bytes)) != -1) {
// 写入文件
outputStream.write(bytes, 0, length);
count += length;
final long finalCount = count;
((Activity) mContext).runOnUiThread(() -> {
// 设置进度条最大值
progressBar.setMax((int) fileLength);
// 设置下载进度
progressBar.setProgress((int) finalCount);
// 设置进度文本 (100 * 当前进度 / 总进度)
tvProgress.setText((int) (100 * finalCount / fileLength) + "%");
});
}
inputStream.close();
outputStream.close();
((Activity) mContext).runOnUiThread(() -> {
//下载完成,自动安装
mDialog.dismiss();
((Activity) mContext).finish();
installApk(new File(Environment.getExternalStorageDirectory() + "/" + "demo.apk"));
});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 安装apk文件
*
* @param apkFile 安装包所在目录
*/
private void installApk(File apkFile) {
//判断版本是否在7.0以上
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri apkUri = FileProvider.getUriForFile(mContext,
"com.carson.fileprovider", apkFile);
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//对目标应用临时授权该Uri所代表的文件
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
install.setDataAndType(apkUri, "application/vnd.android.package-archive");
mContext.startActivity(install);
} else {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(install);
}
}
}
需要在manifest中添加处理
xml下的file_paths
贴上dialog
styles
到此,功能全部实现
最后贴上版本的比较,在后端进行比较后前端最好也进行一次比较,防止错误的出现,进行容错处理
/**
* 如果版本1 大于 版本2 返回true 否则返回fasle 支持 2.2 2.2.1 比较
* 支持不同位数的比较 2.0.0.0.0.1 2.0 对比
*
* @param newVersion 版本服务器版本 " 1.1.2 "
* @param nowVersion 版本 当前版本 " 1.2.1 "
* @return ture :需要更新 false : 不需要更新
*/
public static boolean compareVersions(String newVersion, String nowVersion) {
//判断是否为空数据
if (TextUtils.equals(newVersion, "") || TextUtils.equals(nowVersion, "")) {
return false;
}
String[] str1 = newVersion.split("\\.");
String[] str2 = nowVersion.split("\\.");
if (str1.length == str2.length) {
for (int i = 0; i < str1.length; i++) {
if (Integer.parseInt(str1[i]) > Integer.parseInt(str2[i])) {
return true;
} else if (Integer.parseInt(str1[i]) < Integer.parseInt(str2[i])) {
return false;
} else if (Integer.parseInt(str1[i]) == Integer.parseInt(str2[i])) {
}
}
} else {
if (str1.length > str2.length) {
for (int i = 0; i < str2.length; i++) {
if (Integer.parseInt(str1[i]) > Integer.parseInt(str2[i])) {
return true;
} else if (Integer.parseInt(str1[i]) < Integer.parseInt(str2[i])) {
return false;
} else if (Integer.parseInt(str1[i]) == Integer.parseInt(str2[i])) {
if (str2.length == 1) {
continue;
}
if (i == str2.length - 1) {
for (int j = i; j < str1.length; j++) {
if (Integer.parseInt(str1[j]) != 0) {
return true;
}
if (j == str1.length - 1) {
return false;
}
}
return true;
}
}
}
} else {
for (int i = 0; i < str1.length; i++) {
if (Integer.parseInt(str1[i]) > Integer.parseInt(str2[i])) {
return true;
} else if (Integer.parseInt(str1[i]) < Integer.parseInt(str2[i])) {
return false;
} else if (Integer.parseInt(str1[i]) == Integer.parseInt(str2[i])) {
if (str1.length == 1) {
continue;
}
if (i == str1.length - 1) {
return false;
}
}
}
}
}
return false;
}
代码传送门