使用 compareTo 增加应用程序版本名称

increasing app versionName using a compareTo

我使用一个 android 应用程序(我们可以称之为 "AppA")来更新另一个应用程序(我们可以称之为 "AppB")。 应用程序 "AppA" 检查 "AppB" 的版本名称,如果它较低则开始更新。

我使用本机函数 "compareTo" 检查版本名称。所以这是我的问题: "AppB" versionName 是 9.9,最新的 versionName 是 9.10 但更新没有开始,因为 "compareTo" 函数结果是“9.9 > 9.10”。 即使我使用像“10.9”或“9.100”这样的新版本名称,9.9 总是更大。

我应该放什么?

您可以使用版本名称 9.9.1 来更新它,因为 "9.9".compareTo("9.9.1") < 0.

您也可以使用 9.909.91,因为字符串越长越新。


对于新的更新,您应该发布一个新的比较器,它会查看每个组件,例如:

int[] compOld = new int[3];
String[] split = versionOld.split(".");
for (int i = 0; i < split.length; i++)
    compOld = Integer.parseInt(split[i]);
int[] compNew = new int[3]
...
return compOld[0] < compNew[0] || compOld[1] < compNew[1] || compOld[2] < compNew[2];

或者查看用于语义版本控制的库。

您可以编写自己的函数来比较此类版本字符串:

int compare(String version1, String version2) {
    String[] split1 = version1.split("\.");
    String[] split2 = version2.split("\.");  // split by dot delimeter
    for (int i = 0; i < Math.min(split1.length, split2.length); i++) {
        int number1 = Integer.parseInt(split1[i]);
        int number2 = Integer.parseInt(split2[i]);

        if (number1 < number2) {
            return -1;
        }
        else if (number1 > number2) {
            return 1;
        }
    }
    if (split1.length < split2.length) {
        return -1;
    }
    if (split1.length > split2.length) {
        return 1;
    }
    return 0;
}