判断是否能连接上服务器的方法

  /**

* <p>判断目标服务器是否可以连接函数(调用时host写网址,如"www.baidu.com")</p>
* @param host 注意,不能加http
* @return
* @return boolean   返回类型
* @date 2016-4-15 下午5:09:59
*/


public static boolean isReachqy(String host, int port) {
try {
java.net.Socket socket = new java.net.Socket();
//利用3秒来检查
socket.connect(new InetSocketAddress(host, port), 3000);
} catch (Exception e) {
return false;
}
return true;

}


上面的方法要启动线程来调用

比如在onCreate 里面这么写

new Thread() {
@Override
public void run() {
//你要执行的方法

boolean result = Tools.isReachqy("183.203.255.123", 7001);
//执行完毕后给handler发送一个空消息
if (result) {
handler.sendEmptyMessage(0);
} else {
handler.sendEmptyMessage(1);
}


}
}.start();


/**
* 处理点击进入系统的handler
*/
Handler handler = new Handler() {


@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);


switch (msg.what) {
case 11:
StartNextActivity();
break;
case 0:
initLoading();
break;
case 1:
checkUpdate();
break;


}


}
};


猜你喜欢

转载自blog.csdn.net/ylj15503473366/article/details/51177963