Android系統下檢測Wifi連接互聯網是否正常的代碼

dw23 9年前發布 | 1K 次閱讀 Java Android

/*
 

  • 判斷網絡狀態是否可用 *
  • @return true: 網絡可用 ; false: 網絡不可用 */

public boolean isConnectInternet() { ConnectivityManager conManager = (ConnectivityManager) test.this .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = conManager.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isConnected()) { return false; } if (networkInfo.isConnected()) { return true; } return false; } / 檢查網絡聯機是否正常 / public boolean checkInternetConnection(String strURL, String strEncoding) { / 最多延時n秒若無響應則表示無法聯機 / int intTimeout = 10; try { HttpURLConnection urlConnection = null; URL url = new URL(strURL); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0"

            + " (compatible; MSIE 6.0; Windows 2000)");

    urlConnection.setRequestProperty("Content-type",
            "text/html; charset=" + strEncoding);
    urlConnection.setConnectTimeout(1000 * intTimeout);
    urlConnection.connect();
    if (urlConnection.getResponseCode() == 200)
    {
        return true;
    }
    else
    {
        Log.d("getResponseCode=", urlConnection.getResponseMessage());

        return false;
    }
}
catch (Exception e)
{
    e.printStackTrace();
    Log.d("emessage", e.getMessage());
    return false;
}

}

/ 自定義BIG5轉UTF-8 / public String big52unicode(String strBIG5) { String strReturn = ""; try { strReturn = new String(strBIG5.getBytes("big5"), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return strReturn; }

/ 自定義UTF-8轉BIG5 / public String unicode2big5(String strUTF8) { String strReturn = ""; try { strReturn = new String(strUTF8.getBytes("UTF-8"), "big5"); } catch (Exception e) { e.printStackTrace(); } return strReturn; }</pre>

 本文由用戶 dw23 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!