使用SmartGWT或GWT检查Internet连接



我们如何检查应用程序中是否存在SmartGWT或GWT中的Internet连接?我必须确定是否有互联网连接,并根据这一点将互联网连接的图标更改为绿色或红色,那么有没有办法在SmartGWT或GWT中做到这一点?

您可以创建一个本地方法,在该方法中创建一个新的图像对象(new image()),并将处理程序附加到它的onload和oneror属性。您可以将图像的src属性指向某个您认为表示处于联机状态的URL。然后,通过onload和oneror方法,您可以调用GWT组件中的方法来更新连接指示器。在设置了img.onload和img.oneror.之后,您需要设置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";
}-*/;

我认为导航程序.onLine将帮助您:

http://html5demos.com/offline

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

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

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

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/stackoverflow/img/apple-touch-icon.png?v=41f6e13ade69&state="+Math.floor(Math.random() * 100);
}-*/;
}

希望它对您有效

最新更新