- AppVersionUtil
/**
* @author caowencao
*/
public class AppVersionUtil {
/**
* 比较APP版本号的大小
* <p>
* 1、前者大则返回一个正数
* 2、后者大返回一个负数
* 3、相等则返回0
*
* @param sourceVersion app取出来版本号
* @param targetVersion app发版目标版本号
* @return int
*/
public static int compareAppVersion(String sourceVersion, String targetVersion) {
if (sourceVersion == null || targetVersion == null) {
throw new RuntimeException("版本号不能为空");
}
// 注意此处为正则匹配,不能用.
String[] versionArray1 = sourceVersion.split("\\.");
String[] versionArray2 = targetVersion.split("\\.");
int idx = 0;
// 取数组最小长度值
int minLength = Math.min(versionArray1.length, versionArray2.length);
int diff = 0;
// 先比较长度,再比较字符
while (idx < minLength
&& (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0
&& (diff = versionArray1[idx].compareTo(versionArray2[idx])) == 0) {
++idx;
}
// 如果已经分出大小,则直接返回,如果未分出大小,则再比较位数,有子版本的为大
diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length;
return diff;
}
/**
*
* 1.sourceVersion - targetVersion < 0 ,说明APP传过来的版本号为旧版本
* 2.sourceVersion - targetVersion >= 0 ,说明APP传过来的版本号为当前版本或高于当前版本
* @param sourceVersion APP header来源版本号
* @param targetVersion App发版目标版本号
* @return
*/
public static boolean lowerThan(String sourceVersion, String targetVersion){
return compareAppVersion(sourceVersion,targetVersion) < 0;
}
/**
*
* 1.sourceVersion - targetVersion < 0 , 说明APP传过来的版本号为旧版本
* 2.sourceVersion - targetVersion >= 0 ,说明APP传过来的版本号为当前版本或高于当前版本
* @param sourceVersion APP header来源版本号
* @param targetVersion App发版目标版本号
* @return
* @return sourceVersion - targetVersion >= 0 ,说明APP传过来的版本号为当前版本或高于当前版本
*/
public static boolean notLowerThan(String sourceVersion, String targetVersion){
return compareAppVersion(sourceVersion,targetVersion) >= 0;
}
public static void main(String[] args) {
String v2 ="3.8.101111.1";
// System.out.println(VersionUtil.compareAppVersion("2.8.8",v2));
// System.out.println(VersionUtil.compareAppVersion("2.8.8",v2)>0);
System.out.println(lowerThan("3.9.1",v2));
}
}