Use Java code to compare Android client version Numbers

  • 2020-04-01 04:04:59
  • OfStack

The key point

      Why can't you use the String.compareTo method to compare client version Numbers?

      For example, the previous client version number was 9.9.9, while the latest client version number on the server side was 10.0.1. Although 10.0.1 is obviously higher than 9.9.9, according to the compareTo method, this 9.9.9 is greater than 10.0.1, resulting in an error in comparing the client version number.

Java code implementation

Pulled some, finally or to show the code, the following is my client version number comparison code, welcome to make fun of.

     


 public static int compareVersion(String version1, String version2) {
    if (version1.equals(version2)) {
      return 0;
    }

    String[] version1Array = version1.split("\.");
    String[] version2Array = version2.split("\.");

    int index = 0;
    int minLen = Math.min(version1Array.length, version2Array.length);
    int diff = 0;

    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;
    }
  }


Related articles: