首页 > 技术文章 > Android判断网络是否已经连接

lr393993507 原文

 1 // check all network connect, WIFI or mobile
 2 public static boolean isNetworkAvailable(final Context context) {
 3     boolean hasWifoCon = false;
 4     boolean hasMobileCon = false;
 5  
 6     ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
 7     NetworkInfo[] netInfos = cm.getAllNetworkInfo();
 8     for (NetworkInfo net : netInfos) {
 9  
10         String type = net.getTypeName();
11         if (type.equalsIgnoreCase("WIFI")) {
12             LevelLogUtils.getInstance().i(tag, "get Wifi connection");
13             if (net.isConnected()) {
14                 hasWifoCon = true;
15             }
16         }
17  
18         if (type.equalsIgnoreCase("MOBILE")) {
19             LevelLogUtils.getInstance().i(tag, "get Mobile connection");
20             if (net.isConnected()) {
21                 hasMobileCon = true;
22             }
23         }
24     }
25     return hasWifoCon || hasMobileCon;
26  
27 }

推荐阅读