編輯:關於Android編程
App判斷用戶是否聯網是很普遍的需求,實現思路大概有下面幾種
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 開發:繪制多條線,帶緩存,帶觸控的圖表(基金圖表的實現)
對之前的幾篇文章裡的model進行補充後期會把這個功能類,添加到這個框架裡,有興趣的可以下載下來看,這個框架會經常更新:public class BaseFundChar
Android Service總結及詳細介紹
1、Service的種類按運行地點分類: 類別 區別 優點 缺點 應用
Android之——手機黑名單的實現
有了前面幾篇博文作為基礎(《Android之——AIDL小結》、《Android之——AIDL深入》、《Android之&
Android DrawerLayout 抽屜
Android DrawerLayout 抽屜DrawerLayout 在supportV4 Lib中,類似開源slidemenu一樣,DrawerLayout父類為Vi