Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add compare versionCode #22

Open
zmGitHub opened this issue May 14, 2020 · 3 comments
Open

add compare versionCode #22

zmGitHub opened this issue May 14, 2020 · 3 comments

Comments

@zmGitHub
Copy link

String v1 ="1.0.1"

String v2 ="1.0.2"

v1 > v2

@zmGitHub
Copy link
Author

zmGitHub commented May 14, 2020

`

// 0代表相等,1代表version1大于version2,-1代表version1小于version2

  static int compareVersion(String version1, String version2) {
    if (Utils.isEmpty(version1) || Utils.isEmpty(version2)) {
      return 0;
    }
    if (version1 == version2) {
      return 0;
    }

    List<String> v1Arr = version1.split(".");
    List<String> v2Arr = version2.split(".");

    int index = 0;
    // 获取最小长度值
    int minLen = min(v1Arr.length, v2Arr.length);
    int diff = 0;

    while (index < minLen && (diff = getIntByValueStr(v1Arr[index]) - getIntByValueStr(v2Arr[index])) == 0) {
      index++;
    }
    if (diff == 0) {
      // 如果位数不一致,比较多余位数
      for (int i = index; i < v1Arr.length; i++) {
        if (getIntByValueStr(v1Arr[i]) > 0) {
          return 1;
        }
      }

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

`

@Sky24n
Copy link
Owner

Sky24n commented May 14, 2020

一般情况下,版本比较都是放在在服务端的呢,有可能用的versionCode或versionName;升级,强制升级都是服务端在判定。

@hrxiang
Copy link

hrxiang commented Jan 4, 2022

  static int compareVersion(String val1, String val2) {
    var arr1 = val1.split(".");
    var arr2 = val2.split(".");
    int length = arr1.length >= arr2.length ? arr1.length : arr2.length;
    int diff = 0;
    int v1;
    int v2;
    for (int i = 0; i < length; i++) {
      v1 = i < arr1.length ? int.parse(arr1[i]) : 0;
      v2 = i < arr2.length ? int.parse(arr2[i]) : 0;
      diff = v1 - v2;
      if (diff == 0)
        continue;
      else
        return diff > 0 ? 1 : -1;
    }
    return diff;
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants