java 檢查版本號大小
阿新 • • 發佈:2019-02-18
apk開發過程中,需要比較版本號大小,判斷是否需要升級:
一個版本號:Firmware Version: 6.3.148.0
我的做法是先提取數字,儲存為List<Integer>.例如6,3,148,0
然後把新舊兩個版本的List<Integer>逐個取出比較.判斷.
程式碼如下,如有紕漏或者更好的方式,歡迎指教.
private boolean isNewVersion(String version, String curVersion){
//curVersion = "Firmware Version: 6.3.148.0";
//version = "Firmware Version: 6.110.148.999";
Log.v(TAG, "Check json version = "+version+" curVersion = "+curVersion);
if(curVersion == null || version == null){
return false;
}
List<Integer> mcurVersion = getNumbers(curVersion);
List<Integer> mversion = getNumbers(version);
if(mcurVersion == null || mcurVersion.isEmpty()
|| mversion == null || mversion.isEmpty()){
return false;
}
int smallSize = mcurVersion.size()>mversion.size()?mversion.size():mcurVersion.size();
for (int i = 0; i < smallSize; i++) {
if(mversion.get(i).intValue()>mcurVersion.get(i).intValue()){
Log.d(TAG," mcurVersion["+i+"] = "+mcurVersion.get(i));
Log.d(TAG," mversion["+i+"] = "+mversion.get(i));
return true;
}else if(mversion.get(i).intValue()<mcurVersion.get(i).intValue()){
Log.d(TAG," mcurVersion["+i+"] = "+mcurVersion.get(i));
Log.d(TAG," mversion["+i+"] = "+mversion.get(i));
return false;
}
}
return false;
}
private List<Integer> getNumbers(String content) {
List<Integer> digitList = new ArrayList<Integer>();
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
String tempStr = matcher.group(0);
if(tempStr!=null){
digitList.add(Integer.valueOf(tempStr));
}
}
return digitList;
}