获取网络信息需要在AndroidManifest.xml文件中加入相应的权限。
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一个外网。(ping 3次时间比较长)
/* @author suncat