您的代碼看起來不錯,也許會更好地工作,如果還添加urlc.setReadTimeout(TIME_OUT);
下面是代碼我使用它迄今爲止已經捕獲了各種WiFi /移動連接的情況,但沒有互聯網等。
public boolean isNetworksAvailable() {
ConnectivityManager mConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (mConnMgr != null) {
NetworkInfo[] mNetInfo = mConnMgr.getAllNetworkInfo();
if (mNetInfo != null) {
for (int i = 0; i < mNetInfo.length; i++) {
if (mNetInfo[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
這段代碼的作用是環通所有的網絡狀態,以確保找到一個連接狀態,只有這樣isNetworksAvailable()
在isInternetConnected
我們檢查,如果我們可以做一個簡單的HTTP URL連接。
public boolean isInternetConnected(String mUrl) {
final int CONNECTION_TIMEOUT = 2000;
if (isNetworksAvailable()) {
try {
HttpURLConnection mURLConnection = (HttpURLConnection) (new URL(mUrl).openConnection());
mURLConnection.setRequestProperty("User-Agent", "ConnectionTest");
mURLConnection.setRequestProperty("Connection", "close");
mURLConnection.setConnectTimeout(CONNECTION_TIMEOUT);
mURLConnection.setReadTimeout(CONNECTION_TIMEOUT);
mURLConnection.connect();
return (mURLConnection.getResponseCode() == 200);
} catch (IOException ioe) {
Log.e("isInternetConnected", "Exception occured while checking for Internet connection: ", ioe);
}
} else {
Log.e("isInternetConnected", "Not connected to WiFi/Mobile and no Internet available.");
}
return false;
}
此代碼應在AsyncTask使用或以其他方式,你需要在onCreate()
用下面的代碼使用它,例如(但強烈推薦使用的,而不是做UI線程聯網的的AsyncTask)如果
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
測試連接到互聯網:
if (isInternetConnected("http://www.google.com")) {
showToast("Internet connected");
} else {
showToast("No connection to the Internet!");
}
轉到這個http://stackoverflow.com/questions/12889750/how-to-find-network-enable-status-in-android/128900 37#12890037 –
@ user1591982我的回答有幫助嗎? – kaderud
不,對不起。同樣的結果。但非常感謝你的答案! – user1591982