首页 > 解决方案 > 代号一 - 仅在 Internet 连接可用时执行代码

问题描述

是否可以从 EDT 有一个单独的线程,在应用程序启动时启动并仅在 Internet 连接可用时执行一些代码?我的意思是,如果出现连接错误,它不会显示或抛出任何错误或异常,它必须等到连接到它正在工作的服务器。

我的用例是版本检查:将支持的最低应用程序与当前应用程序版本进行比较。

标签: codenameone

解决方案


您不需要单独的线程来执行此操作。您可以只使用一个计时器来轮询您的服务器。如果没有互联网连接,它可能会默默地失败。您可以使用setFailSilently(true)which 吞下来自该特定 URL 的错误。

或者,当连接请求传递给错误事件回调时,您的全局处理代码可以过滤来自该 URL 的错误。例如,此代码在应用启动后 10 秒开始检查,因此它不会减慢启动速度:

        UITimer.timer(10000, false, () -> {
           Server.checkVersion((currentVersion, oldestSupportedVersion) -> {
               float ver = Float.parseFloat(getProperty("AppVersion", "0.1"));
               if(ver < oldestSupportedVersion) {
                   Dialog.show("Error", "This version is out of date!\nPlease update the app from the store!", "Exit", null);
                   exitApplication();
                   return;
               }
               if(currentVersion > ver) {
                   ToastBar.showInfoMessage("A new version of the app is available...");
               }
           });
        });

public static interface VersionCallback {
    public void version(float currentVersion, float oldestSupportedVersion);
}

public static void checkVersion(VersionCallback ver) {
    Rest.
        get(url-to-properties-file-on-server).
        fetchAsBytes(res -> {
            if(res.getResponseCode() == 200) {
                try {
                    Properties p = new Properties();
                    p.load(new ByteArrayInputStream(res.getResponseData()));
                    String currentVer = p.getProperty("app.current","0.15");
                    String lastSupported = p.getProperty("app.lastSupported","0.14");
                    ver.version(Float.parseFloat(currentVer), 
                        Float.parseFloat(lastSupported));
                } catch(IOException err) {
                    Log.e(err);
                }
            }
        });
}

推荐阅读