codenameone - 代号一 - 仅在 Internet 连接可用时执行代码
问题描述
是否可以从 EDT 有一个单独的线程,在应用程序启动时启动并仅在 Internet 连接可用时执行一些代码?我的意思是,如果出现连接错误,它不会显示或抛出任何错误或异常,它必须等到连接到它正在工作的服务器。
我的用例是版本检查:将支持的最低应用程序与当前应用程序版本进行比较。
解决方案
您不需要单独的线程来执行此操作。您可以只使用一个计时器来轮询您的服务器。如果没有互联网连接,它可能会默默地失败。您可以使用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);
}
}
});
}
推荐阅读
- java - 多个 DAO 的房间 runInTransaction
- ssh - Bitbuket 管道 - 如何设置 ssh
- c# - HttpWebRequest C# 的 API 超时错误 | 与邮递员和restsharp一起工作
- apache-spark - ConnectException:从 test/127.0.0.1 到 localhost:9000 的调用失败
- ios - UIDatepicker 用'---'显示未来年份
- html - 在 iOS 上,Safari:如何防止底层页面/主页滚动但超出覆盖范围。覆盖应该能够滚动
- ios - 将对象保存为用户默认值
- javascript - 当 javascript 提示某些内容时,网页变为空白
- java - 无法访问 application.properties 文件
- php - Isset 适用于本地服务器,但不适用于实时服务器