android version number size comparison

Keywords: less Android

As you all know, the version number generally consists of the following parts:

1. Main version number
 2. Minor version number
 3. Revision number
 4. Compiled version number
 For example: 2.1.3, 3.7.5, 10.2.0

When comparing version numbers, the correct way is to compare the major version number with the major version number, compare the minor version number with the minor version number, etc., that is, to divide the version number and compare the corresponding components, as follows:

/**
     * Version number comparison
     * 
     * @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;
        // Get the minimum length value
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // Loop to determine the size of each
        Log.d("HomePageActivity", "verTag2=2222="+version1Array[index]);
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index])
                        - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // If the digits are inconsistent, compare the extra digits
            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;
        }
    }

The result shows that: 0 means equal, 1 means version1 is greater than version2, and - 1 means version1 is less than version2

Through this method, android version number can be compared directly


Posted by rdimaggio on Thu, 02 Apr 2020 15:39:02 -0700