检查网址是否为具有超时响应的Reachable Android

时间:2017-05-04 06:38:25

标签: android

我有写函数来检查地址是否可达,我的问题是当响应很慢或进入超时时它会冻结UI持续时间不接收响应或捕获异常。

我的功能是:

public static boolean isURLReachable() {
   ConnectivityManager cm = (ConnectivityManager) App.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo netInfo = cm.getActiveNetworkInfo();
   if (netInfo != null && netInfo.isConnected()) {
      try {
         StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
         StrictMode.setThreadPolicy(policy);
         URL url = new URL(ConfigData.CHECK_IP); 
         HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                        urlc.setConnectTimeout(TIME_OUT_CALL);
                        urlc.setReadTimeout(TIME_OUT_CALL);
                        urlc.connect();
                        if (urlc.getResponseCode() == 200) {        // 200 = "OK" code (http connection is fine).
                            return true;
                        } else {
                            return false;
                        }
                    } catch (MalformedURLException e1) {
                        return  false;
                    }
                    catch (java.net.SocketTimeoutException e) {
                        return false;
                    } catch (IOException e) {
                        return false;
                    }
                }
                return false;
            }

有一种方法可以阻止用户界面吗?

1 个答案:

答案 0 :(得分:0)

您可以使用Socket:

public static boolean isURLReachable() {
    final  URL url  = new URL("your url here");

     final  Socket socket = new Socket();
                            socket.setSoTimeout(200);
                            socket.connect(new   InetSocketAddress(url.getHost(),url.getPort()),200);
                    isConect =socket.isConnected();
                    socket.close();
            return isConect;
}


where 200 is the required timeout.