获取网络状态
首先在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 11 return false; 12 }
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 //返回值 -1:没有网络 1:WIFI网络2:wap网络3:net网络 2 public static int GetNetype(Context context) { 3 int netType = -1; 4 ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 5 NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 6 if (networkInfo == null) { 7 return netType; 8 } 9 int nType = networkInfo.getType(); 10 if (nType == ConnectivityManager.TYPE_MOBILE) { 11 if (networkInfo.getExtraInfo().toLowerCase().equals("cmnet")) { 12 netType = 3; 13 } else { 14 netType = 2; 15 } 16 } else if (nType == ConnectivityManager.TYPE_WIFI) { 17 netType = 1; 18 } 19 return netType; 20 }