Android本地版本名与服务器版本名比较

public class VersionNameCompareUtil {

/**
 * 版本号比较
 *
 * @param version1
 * @param version2
 * @return
 */
public static int compareVersion(String version1, String version2) {
    if (version1.equals(version2)) {
        return 0;
    }
    String[] version1Array = version1.split("\\.");
    String[] version2Array = version2.split("\\.");
    Log.d("HomePageActivity", "version1Array=="+version1Array.length);
    Log.d("HomePageActivity", "version2Array=="+version2Array.length);
    int index = 0;
    // 获取最小长度值
    int minLen = Math.min(version1Array.length, version2Array.length);
    int diff = 0;
    // 循环判断每位的大小
    Log.d("HomePageActivity", "verTag2=2222="+version1Array[index]);
    while (index < minLen
            && (diff = Integer.parseInt(version1Array[index])
            - Integer.parseInt(version2Array[index])) == 0) {
        index++;
    }
    if (diff == 0) {
        // 如果位数不一致,比较多余位数
        for (int i = index; i < version1Array.length; i++) {
            if (Integer.parseInt(version1Array[i]) > 0) {
                return 1;
            }
        }

        for (int i = index; i < version2Array.length; i++) {
            if (Integer.parseInt(version2Array[i]) > 0) {
                return -1;
            }
        }
        return 0;
    } else {
        return diff > 0 ? 1 : -1;
    }
}

/**
 * 获取版本名称
 *
 * @param context 上下文
 * @return 版本名称
 */
public static String getVersionName(Context context) {

//获取包管理器
PackageManager pm = context.getPackageManager();
//获取包信息
try {
PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
//返回版本号
return packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return null;
}

/**
 * 获取版本號
 * @param context
 * @return
 */
public static int getVersionCodeUtil(Context context) {

    int versionCode = 0;
    try {
        versionCode = context.getPackageManager()//拿到package管理者
                .getPackageInfo(context.getPackageName(), 0).versionCode;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return versionCode;//返回versionCode
}

}

你可能感兴趣的:(Android功能)