C端APP常用版本号判断工具类

AppVersionUtil是一个Java类,用于比较两个Android应用的版本号。它通过将版本号拆分成数组并逐段比较来确定版本的大小关系,支持处理带有额外细分版本号的情况。类中包含compareAppVersion方法进行比较以及lowerThan和notLowerThan方法判断版本是否小于或不低于目标版本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • AppVersionUtil
/**
 * @author caowencao
 */
public class AppVersionUtil {

    /**
     * 比较APP版本号的大小
     * <p>
     * 1、前者大则返回一个正数
     * 2、后者大返回一个负数
     * 3、相等则返回0
     *
     * @param sourceVersion app取出来版本号
     * @param targetVersion app发版目标版本号
     * @return int
     */
    public static int compareAppVersion(String sourceVersion, String targetVersion) {
        if (sourceVersion == null || targetVersion == null) {
            throw new RuntimeException("版本号不能为空");
        }
        // 注意此处为正则匹配,不能用.
        String[] versionArray1 = sourceVersion.split("\\.");
        String[] versionArray2 = targetVersion.split("\\.");
        int idx = 0;
        // 取数组最小长度值
        int minLength = Math.min(versionArray1.length, versionArray2.length);
        int diff = 0;
        // 先比较长度,再比较字符
        while (idx < minLength
                && (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0
                && (diff = versionArray1[idx].compareTo(versionArray2[idx])) == 0) {
            ++idx;
        }
        // 如果已经分出大小,则直接返回,如果未分出大小,则再比较位数,有子版本的为大
        diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length;
        return diff;
    }

    /**
     *
     * 1.sourceVersion - targetVersion < 0  ,说明APP传过来的版本号为旧版本
     * 2.sourceVersion - targetVersion >= 0 ,说明APP传过来的版本号为当前版本或高于当前版本
     * @param sourceVersion  APP header来源版本号
     * @param targetVersion  App发版目标版本号
     * @return
     */
    public static boolean lowerThan(String sourceVersion, String targetVersion){
        return compareAppVersion(sourceVersion,targetVersion) < 0;
    }


    /**
     *
     * 1.sourceVersion - targetVersion < 0 , 说明APP传过来的版本号为旧版本
     * 2.sourceVersion - targetVersion >= 0 ,说明APP传过来的版本号为当前版本或高于当前版本
     * @param sourceVersion  APP header来源版本号
     * @param targetVersion  App发版目标版本号
     * @return
     * @return  sourceVersion - targetVersion >= 0 ,说明APP传过来的版本号为当前版本或高于当前版本
     */
    public static boolean notLowerThan(String sourceVersion, String targetVersion){
        return compareAppVersion(sourceVersion,targetVersion) >= 0;
    }

    public static void main(String[] args) {
        String v2 ="3.8.101111.1";
//        System.out.println(VersionUtil.compareAppVersion("2.8.8",v2));
//        System.out.println(VersionUtil.compareAppVersion("2.8.8",v2)>0);

        System.out.println(lowerThan("3.9.1",v2));
    }

}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Thinkingcao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值