Connectivitymanager function: monitors the network connection status
Use the context. getsystemservice (context. connectivity_service); method to obtain,
Permission required: Android. Permission. access_network_state
Common Methods:
1. getallnetworkinfo () // obtain all network connection information
2. getactivenetworkinfo () // get the information of the network that is being connected.
3. getnetworkinfo (INT networktype) // obtain the information of the specified network connection type
Networktype: connectivitymanage. type_wifi; connectivitymanage. type_mobile
Getallnetworkinfo () instance:
public static boolean isNetworkAvailable(Activity mActivity){Context context = mActivity.getApplicationContext();ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);if(connectivity == null){return false;}else {NetworkInfo[] info = connectivity.getAllNetworkInfo();if(info != null ){for(int i=0; i<info.length; i++){if(info[i].getState() == NetworkInfo.State.CONNECTED){return true;}}}}return false;}
Getactivenetworkinfo () instance:
Public static Boolean isnetworkavailable (activity mactivity) {context = mactivity. getapplicationcontext (); connectivitymanager connectivity = (connectivitymanager) context. getsystemservice (context. connectivity_service); networkinfo = connectivity. getactivenetworkinfo (); // obtain whether the current network connection is available // determine the network type networkinfo. getType () = connectivitymanager. type_mobile if (networkinfo. isavailable () return true; else return false;
Getnetworkinfo (INT networktype) instance:
public static boolean isNetworkAvailable(Activity mActivity){Context context = mActivity.getApplicationContext(); ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService( Context.CONNECTIVITY_SERVICE);if(State.CONNECTED==connectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState()) return true;if(State.CONNECTED==connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState()) return true;else return false; }
Six States:
Public static final networkinfo. State connected
Public static final networkinfo. State connecting
Public static final networkinfo. State disconnected
Public static final networkinfo. State Disconnecting
Public static final networkinfo. State susponded
Public static final networkinfo. State unknown