获取网络信息需要在AndroidManifest.xml文件中加入相应的权限。
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
1)判断是否有网络连接
1 public boolean isNetworkConnected(Context context) { 2 if (context != null) { 3 ConnectivityManager mConnectivityManager = (ConnectivityManager) context 4 .getSystemService(Context.CONNECTIVITY_SERVICE); 5 NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); 6 if (mNetworkInfo != null) { 7 return mNetworkInfo.isAvailable(); 8 } 9 } 10 return false; 11 }
2)判断WIFI网络是否可用
1 public boolean isWifiConnected(Context context) { 2 if (context != null) { 3 ConnectivityManager mConnectivityManager = (ConnectivityManager) context 4 .getSystemService(Context.CONNECTIVITY_SERVICE); 5 NetworkInfo mWiFiNetworkInfo = mConnectivityManager 6 .getNetworkInfo(ConnectivityManager.TYPE_WIFI); 7 if (mWiFiNetworkInfo != null) { 8 return mWiFiNetworkInfo.isAvailable(); 9 } 10 } 11 return false; 12 }
3)判断MOBILE网络是否可用
1 public boolean isMobileConnected(Context context) { 2 if (context != null) { 3 ConnectivityManager mConnectivityManager = (ConnectivityManager) context 4 .getSystemService(Context.CONNECTIVITY_SERVICE); 5 NetworkInfo mMobileNetworkInfo = mConnectivityManager 6 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 7 if (mMobileNetworkInfo != null) { 8 return mMobileNetworkInfo.isAvailable(); 9 } 10 } 11 return false; 12 }
4)获取当前网络连接的类型信息
1 public static int getConnectedType(Context context) { 2 if (context != null) { 3 ConnectivityManager mConnectivityManager = (ConnectivityManager) context 4 .getSystemService(Context.CONNECTIVITY_SERVICE); 5 NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); 6 if (mNetworkInfo != null && mNetworkInfo.isAvailable()) { 7 return mNetworkInfo.getType(); 8 } 9 } 10 return -1; 11 }
有时候我们连接上一个没有外网连接的WiFi或者有线就会出现这种极端的情况,目前Android SDK还不能识别这种情况,一般的解决办法就是ping一个外网。
1 /* @author suncat 2 * @category 判断是否有外网连接(普通方法不能判断外网的网络是否连接,比如连接上局域网) 3 * @return 4 */ 5 public static final boolean ping() { 6 7 String result = null; 8 try { 9 String ip = "www.baidu.com";// ping 的地址,可以换成任何一种可靠的外网 10 Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次 11 // 读取ping的内容,可以不加 12 InputStream input = p.getInputStream(); 13 BufferedReader in = new BufferedReader(new InputStreamReader(input)); 14 StringBuffer stringBuffer = new StringBuffer(); 15 String content = ""; 16 while ((content = in.readLine()) != null) { 17 stringBuffer.append(content); 18 } 19 Log.d("------ping-----", "result content : " + stringBuffer.toString()); 20 // ping的状态 21 int status = p.waitFor(); 22 if (status == 0) { 23 result = "success"; 24 return true; 25 } else { 26 result = "failed"; 27 } 28 } catch (IOException e) { 29 result = "IOException"; 30 } catch (InterruptedException e) { 31 result = "InterruptedException"; 32 } finally { 33 Log.d("----result---", "result = " + result); 34 } 35 return false; 36 }