使用 SmartGWT 或 GWT 检查 Internet 连接?

Checking Internet Connection using SmartGWT or GWT?

在 SmartGWT 或 GWT 中,我们如何检查应用程序中是否存在 Internet 连接?我必须确定是否存在 Internet 连接,并根据此将 Internet 连接的图标更改为绿色或红色,那么有没有办法在 SmartGWT 或 GWT 中执行此操作?

我认为 navigator.onLine 会对您有所帮助:

http://html5demos.com/offline

http://www.html5rocks.com/en/features/offline

您可能需要将调用包装到 JSNI 中并实现事件侦听器。

public native Boolean isOnline()/*-{
    return window.onLine;
}-*/;

您可以创建一个本机方法,在该方法中创建一个新图像对象 (new Image()) 并将处理程序附加到它的 onload 和 onerror 属性。您可以将图片的 src 属性 指向您认为在线的某些 URL。然后,您可以从您的 onload 和 onerror 方法调用 GWT 组件中的方法来更新您的连接指示器。设置img.onload和img.onerror后需要设置img.src。

例如:

native void checkConnectivity(Example obj) /*-{
    var img = new Image();
    img.onload = function() {           
      obj.@com.example.client.Example::online()();
    }
    img.onerror = function() {                    
      obj.@com.example.client.Example::offline()();
    }
    img.src = "http://exampleapp.com/test.gif";
}-*/;

Udeleng 的解决方案是我最接近跨浏览器的方法。我一直在 FF 18 上测试它,但我相信它可以在任何浏览器中运行。

但是请注意,当您调用 new Image() 时,浏览器会预加载图像,将其缓存起来,以便后续对同一 URL 的调用不会进行 HTTP 调用。这会破坏我们想要实现的效果,即从 offlineonline 状态的转换有效,但是一旦浏览器获得任何连接,图像就会被缓存,故事结束,即使你拔掉你的以太网电缆。

解决方案 在 URL 中添加一个状态参数并给它一个随机数,这个想法是欺骗浏览器认为它是一个新图像,这样图像每次都从服务器获取,而不是从缓存中获取。

当然要加上定时器。这是我的代码:

import com.google.gwt.core.shared.GWT;
import com.google.gwt.user.client.Timer;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Img;
import com.smartgwt.client.widgets.events.DrawEvent;
import com.smartgwt.client.widgets.events.DrawHandler;
public class WebConnChecker extends Img {
 private static final String ONLINE="online_stat.jpg";
 private static final String OFFLINE="offline_stat.jpg";
 private static final int INTERVAL=10000;
 private Timer timer;

 public WebConnChecker(){
  setSize(16);
  timer=new Timer() {
   @Override
   public void run() {
    checkConnectivity(WebConnChecker.this);
   }
  };
  addDrawHandler(new DrawHandler() {
   
   @Override
   public void onDraw(DrawEvent event) {
    timer.scheduleRepeating(INTERVAL);

   }
  });  
 }
 private void online(){
  log("online detected");
  this.setSrc(ONLINE);
 }
 private void offline(){
  log("offline detected");
  this.setSrc(OFFLINE);
 }

 private native void checkConnectivity(WebConnChecker checker) /*-{
    var img = new Image();
    img.onload = function() { 
     window.alert("online");          
      checker.@com.telligent.smap.student.client.util.WebConnChecker::online()();
    }
    img.onerror = function() {  
        window.alert("offline");                
      checker.@com.telligent.smap.student.client.util.WebConnChecker::offline()();
    }
    img.src = "http://cdn.sstatic.net/Whosebug/img/apple-touch-icon.png?v=41f6e13ade69&state="+Math.floor(Math.random() * 100);
}-*/;
}

希望对你有用