You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:如何读取URL文本并与指定字符串对比实现更新检测

实现方案

你只需要在逐行读取URL返回内容的时候,把每行内容追加到StringBuilder容器中,就能得到完整的可用于后续对比的字符串,改造后的可直接用于版本检测的代码如下:

package com.javacodegeeks.snippets.core;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
 
public class UpdateChecker {
    // 本地预置的当前版本号
    private static final String LOCAL_VERSION = "1.0.0";
    // pastebin raw格式的版本号链接
    private static final String VERSION_URL = "你的pastebin raw链接地址";
    // 更新下载链接
    private static final String DOWNLOAD_URL = "你的应用下载地址";
     
    public static void main(String[] args) {
        String remoteVersion = getRemoteContent(VERSION_URL);
        if (remoteVersion == null) {
            // 拉取失败的处理逻辑,比如跳过本次检测
            return;
        }
        // 去掉首尾空白字符避免格式问题
        remoteVersion = remoteVersion.trim();
        if (!remoteVersion.equals(LOCAL_VERSION)) {
            // 这里写触发更新弹窗的逻辑,展示下载链接
            System.out.println("检测到新版本:" + remoteVersion);
            System.out.println("下载地址:" + DOWNLOAD_URL);
        }
    }

    // 封装方法:从指定URL拉取文本内容,拉取失败返回null
    private static String getRemoteContent(String urlStr) {
        StringBuilder contentBuilder = new StringBuilder();
        try {
            URL url = new URL(urlStr);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            while ((line = in.readLine()) != null) {
                contentBuilder.append(line).append("\n");
            }
            in.close();
            return contentBuilder.toString();
        } catch (MalformedURLException e) {
            System.out.println("URL格式错误:" + e.getMessage());
        } catch (IOException e) {
            System.out.println("网络请求错误:" + e.getMessage());
        }
        return null;
    }
}

注意事项

  • 如果是Android应用,不要在UI主线程执行上述网络请求逻辑,需要放在子线程、协程或者异步任务中执行,避免触发ANR错误,同时需要在清单文件中添加android.permission.INTERNET网络权限
  • pastebin的raw链接需要设置为公开无权限访问,否则会拉取失败
  • 版本号尽量统一命名规则,比如都采用主版本号.次版本号.修订号的格式,避免对比出错

内容的提问来源于stack exchange,提问作者Vojtěch Adam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 19:54:09