Public static Boolean isnetworkavailable (context) {connectivitymanager connectivity = (connectivitymanager) context. getsystemservice (context. connectivity_service); If (connectivity = NULL) {log. I ("networkstate", "unavailabel"); 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) {log. I ("networkstate", "availabel"); Return true ;}}} return false ;}
The above method is to determine whether the network is connected.Code, Returns true to indicate that there is a network, returns false to indicate that there is no network. Android network applicationsProgramDuring development, it is often necessary to determine whether the network connection is available, so it is often necessary to listen to changes in the network status. For android network status monitoring, broadcastreceiver can be used to receive broadcast requests with network status changes. The specific implementation is as follows:
@ Overridepublic void onreceive (context, intent) {log. E (TAG, "network status change"); Boolean success = false; // get the network connection service connectivitymanager connmanager = (connectivitymanager) getsystemservice (connectivity_service); // state = connmanager. getactivenetworkinfo (). getstate (); State state = connmanager. getnetworkinfo (connectivitymanager. type_wifi ). getstate (); // get the network connection status if (state. connected = State) {// Determine whether the WiFi network is being used success = true;} state = connmanager. getnetworkinfo (connectivitymanager. type_mobile ). getstate (); // get the network connection status if (state. connected! = State) {// determine whether the GPRS network Success = true;} If (! Success) {toast. maketext (locationmapactivity. This, "your network connection has been interrupted", Toast. length_long). Show ();}}
In oncreate of activity:
// register the network listener intentfilter filter = new intentfilter (); filter. addaction (connectivitymanager. connectivity_action); registerreceiver (mnetworkstatereceiver, filter); // In ondestroy of activity: 'unregisterreceiver (mnetworkstatereceiver); // cancel the listener