Android 判斷 網絡連接 Internet訪問 工具類

yyuu1411 8年前發布 | 7K 次閱讀 Java Android

前言

App判斷用戶是否聯網是很普遍的需求,實現思路大概有下面幾種

  • 利用Android自帶的ConnectivityManager類
  • 有時候連上了wifi,但這個wifi是上不了網的,我們可以通過ping www.baidu.com來判斷是否可以上網
  • 也可以利用get請求訪問www.baidu.com,如果get請求成功,說明可以上網

文章鏈接 http://blog.csdn.net/never_cxb/article/details/47658257

Android 判斷 網絡連接

判斷網絡是否已經連接

// check all network connect, WIFI or mobile
public static boolean isNetworkAvailable(final Context context) {
    boolean hasWifoCon = false;
    boolean hasMobileCon = false;

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfos = cm.getAllNetworkInfo();
    for (NetworkInfo net : netInfos) {

        String type = net.getTypeName();
        if (type.equalsIgnoreCase("WIFI")) {
            LevelLogUtils.getInstance().i(tag, "get Wifi connection");
            if (net.isConnected()) {
                hasWifoCon = true;
            }
        }

        if (type.equalsIgnoreCase("MOBILE")) {
            LevelLogUtils.getInstance().i(tag, "get Mobile connection");
            if (net.isConnected()) {
                hasMobileCon = true;
            }
        }
    }
    return hasWifoCon || hasMobileCon;

}

利用 ping 判斷 Internet 能夠 請求成功

Note

有時候連上了網絡, 但卻上不去外網

// network available cannot ensure Internet is available
public static boolean isNetWorkAvailable(final Context context) {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process pingProcess = runtime.exec("/system/bin/ping -c 1 www.baidu.com");
        int exitCode = pingProcess.waitFor();
        return (exitCode == 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

考慮到網絡, 我們 ping 了www.baidu.com

國外的話可以 ping 8.8.8.8

其他方案 模擬 get 請求

也可以訪問網址, 看 get 請求能不能成功

 URL url = new URL("http://www.google.com");
 HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
 urlc.setConnectTimeout(3000);
 urlc.connect();
 if (urlc.getResponseCode() == 200) {
     return new Boolean(true);
 }

疑惑點

stackoverflow 也是這么寫的 type.equalsIgnoreCase(“WIFI”)
我疑惑這個 “WIFI” 為什么是硬編碼

如果文章對您有幫助,請賞注彩票錢^=^

支付寶

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