Android中判斷網(wǎng)絡(luò)連接狀態(tài)的方法
App判斷用戶是否聯(lián)網(wǎng)是很普遍的需求,實(shí)現(xiàn)思路大概有下面幾種
- 利用Android自帶的ConnectivityManager類
- 有時(shí)候連上了wifi,但這個(gè)wifi是上不了網(wǎng)的,我們可以通過ping www.baidu.com來判斷是否可以上網(wǎng)
- 也可以利用get請求訪問www.baidu.com,如果get請求成功,說明可以上網(wǎng)
1、判斷網(wǎng)絡(luò)是否已經(jīng)連接
// 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; }
2、利用 ping 判斷 Internet 能夠 請求成功
Note:有時(shí)候連上了網(wǎng)絡(luò), 但卻上不去外網(wǎng)
// 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; }
考慮到網(wǎng)絡(luò), 我們 ping 了www.baidu.com
國外的話可以 ping 8.8.8.8
3、其他方案 模擬 get 請求
也可以訪問網(wǎng)址, 看 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); }
以上就是本文的全部內(nèi)容,希望對大家學(xué)習(xí)Android軟件編程有所幫助。
- Android中判斷網(wǎng)絡(luò)連接是否可用及監(jiān)控網(wǎng)絡(luò)狀態(tài)
- android 檢查網(wǎng)絡(luò)連接狀態(tài)實(shí)現(xiàn)步驟
- Android中監(jiān)聽判斷網(wǎng)絡(luò)連接狀態(tài)的方法
- android檢測網(wǎng)絡(luò)連接狀態(tài)示例講解
- Android中檢查網(wǎng)絡(luò)連接狀態(tài)的變化無網(wǎng)絡(luò)時(shí)跳轉(zhuǎn)到設(shè)置界面
- Android使用BroadcastReceiver監(jiān)聽網(wǎng)絡(luò)連接狀態(tài)的改變
- Android獲取網(wǎng)絡(luò)連接狀態(tài)新方法整理
相關(guān)文章
Android強(qiáng)制下線功能實(shí)現(xiàn)的代碼示例
本篇文章主要介紹了Android強(qiáng)制下線功能實(shí)現(xiàn)的代碼示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02安裝時(shí)加入外部數(shù)據(jù)庫示例(android外部數(shù)據(jù)庫)
這篇文章主要介紹了android打包安裝時(shí)加入外部數(shù)據(jù)庫的示例,需要的朋友可以參考下2014-03-03Input系統(tǒng)截?cái)嗖呗缘姆治雠c應(yīng)用詳解
這篇文章主要為大家介紹了Input系統(tǒng)截?cái)嗖呗缘姆治雠c應(yīng)用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02Android開源項(xiàng)目PullToRefresh下拉刷新功能詳解2
這篇文章主要為大家進(jìn)一步的介紹了Android開源項(xiàng)目PullToRefresh下拉刷新功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09Android webview轉(zhuǎn)PDF的方法示例
本篇文章主要介紹了Android webview轉(zhuǎn)PDF的方法示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-01-01