import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import java.util.HashMap;
/**
* 앱 버전 체크 유틸
*/
public class VersionUtil {
/**
* EQUALS 버전이 동일함
* UPDATE 현재 버전이 구 버전 이며 업데이트가 필요하다.
* NEW 해당 버전 보다 높은 버전 이다.
* */
public enum VERSION_CODE {
EQUALS(0), UPDATE(-1), NEW(1);
private static HashMap<Integer, VERSION_CODE> codeHashMap;
static {
codeHashMap = new HashMap<>();
for (VERSION_CODE value : VERSION_CODE.values()) {
codeHashMap.put(value.getValue(), value);
}
}
protected static VERSION_CODE fromVersionCode(int value) {
return codeHashMap.get(value);
}
int value;
public int getValue() {
return value;
}
VERSION_CODE(int value) {
this.value = value;
}
}
/**
* @param appVersion 현 어플리케이션의 버전
* @param serverVersion 서버로부터 전달받은 최신 버전명
* @return VERSION_CODE {@link VERSION_CODE}
*/
public static VERSION_CODE CheckVersion(String appVersion, String serverVersion) {
Version app = new Version(appVersion);
Version server = new Version(serverVersion);
int result = app.compareTo(server);
return VERSION_CODE.fromVersionCode(result);
}
public static String getAppVersion(Context context){
// application version
String versionName = "";
try {
PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
versionName = info.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}
private static class Version implements Comparable<Version> {
private String version;
public final String get() {
return this.version;
}
public Version(String version) {
if (version == null)
throw new IllegalArgumentException("Version can not be null");
if (!version.matches("[0-9]+(\\.[0-9]+)*"))
throw new IllegalArgumentException("Invalid version format");
this.version = version;
}
@Override
public int compareTo(Version that) {
if (that == null)
return 1;
String[] thisParts = this.get().split("\\.");
String[] thatParts = that.get().split("\\.");
int length = Math.max(thisParts.length, thatParts.length);
for (int i = 0; i < length; i++) {
int thisPart = i < thisParts.length ?
Integer.parseInt(thisParts[i]) : 0;
int thatPart = i < thatParts.length ?
Integer.parseInt(thatParts[i]) : 0;
if (thisPart < thatPart)
return -1;
if (thisPart > thatPart)
return 1;
}
return 0;
}
@Override
public boolean equals(Object that) {
if (this == that)
return true;
if (that == null)
return false;
if (this.getClass() != that.getClass())
return false;
return this.compareTo((Version) that) == 0;
}
}
}
VersionUtil.VERSION_CODE versionCode = VersionUtil.CheckVersion(VersionUtil.getAppVersion(this), result.getVersion().trim());
끝~