0
我有寫功能,檢查地址是否可達或不,我的問題是,當響應速度慢或進入超時它凍結用戶界面長時間不接收響應或趕上例外。檢查網址是否可達Android有超時響應
我的功能是:
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;
}
有一種辦法不阻止用戶界面?
你好三江源! 它返回IllegalArgumentException主機錯誤 – LorenzoBerti
您的網址是「http://stackoverflow.com/」或「http://127.0.0.1/」? –
我試了兩個,調試似乎錯誤是在socket.connect() 現在我有這個:socket.connect(新InetSocketAddress(「192.168.1.20」,80),2000); – LorenzoBerti