Android中判斷網絡連接狀態(tài)的方法
更新時間:2016年02月13日 16:27:39 投稿:lijiao
App判斷用戶是否聯網是很普遍的需求,這篇文章主要介紹了Android中判斷網絡連接狀態(tài)的方法,感興趣的朋友可以參考一下
App判斷用戶是否聯網是很普遍的需求,實現思路大概有下面幾種
- 利用Android自帶的ConnectivityManager類
- 有時候連上了wifi,但這個wifi是上不了網的,我們可以通過ping www.baidu.com來判斷是否可以上網
- 也可以利用get請求訪問www.baidu.com,如果get請求成功,說明可以上網
1、判斷網絡是否已經連接
// 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:有時候連上了網絡, 但卻上不去外網
// 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
3、其他方案 模擬 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);
}
以上就是本文的全部內容,希望對大家學習Android軟件編程有所幫助。
相關文章
Android開源項目PullToRefresh下拉刷新功能詳解2
這篇文章主要為大家進一步的介紹了Android開源項目PullToRefresh下拉刷新功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09

