HTML code
- public static Boolean isnetworkavailable (context 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 connection code, return True indicates that there is a network, return false indicates no network. In the development of Android Web applications, it is often necessary to determine whether a network connection is available, so it is often important to listen for changes in network status. Android Network status monitoring can use Broadcastreceiver to receive network status changes broadcast, the implementation of the following:
HTML code
- @Override
- public void OnReceive (context context, Intent Intent) {
- LOG.E (TAG, "Network status change");
- Boolean success = false;
- Access to network connectivity services
- Connectivitymanager Connmanager = (connectivitymanager) getsystemservice (Connectivity_service);
- State state = connmanager.getactivenetworkinfo (). GetState ();
- State state = Connmanager.getnetworkinfo (
- Connectivitymanager.type_wifi). GetState (); Get Network Connection Status
- if (state.connected = = state) {//Determine if WiFi network is in use
- Success = true;
- }
- State = Connmanager.getnetworkinfo (
- Connectivitymanager.type_mobile). GetState (); Get Network Connection Status
- if (state.connected! = state) {//Determine if GPRS network is being used
- Success = true;
- }
- if (!success) {
- Toast.maketext (Locationmapactivity.this, "Your network connection has been interrupted", Toast.length_long). Show ();
- }
- }
In the OnCreate of activity:
HTML code
- //register Network Monitor
- intentfilter < span class= "attribute" >filter = new intentfilter ();
- filter.addaction (connectivitymanager.connectivity_action);
- Registerreceiver (mnetworkstatereceiver, filter);
- //OnDestroy in activity: '
-
- unregisterreceiver (mnetworkstatereceiver); //Cancel monitoring