Android Check network status step

Source: Internet
Author: User

How Android checks the status of the network connection is a common problem in Android development.

Obtaining network information requires the appropriate permissions to be added to the Androidmanifest.xml file:

<span style= "FONT-SIZE:24PX;" ><uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/> </span>
1) Determine if there is an Internet connection
<span style= "FONT-SIZE:24PX;" >public Boolean isnetworkconnected (context context) {     if (context! = null) {         Connectivitymanager Mconnectivitymanager = (connectivitymanager) context                 . Getsystemservice (context.connectivity_service);         Networkinfo mnetworkinfo = Mconnectivitymanager.getactivenetworkinfo ();        if (mnetworkinfo! = null) {           return mnetworkinfo.isavailable ();}         }        return false; } </span>

2) determine if the WiFi network is available

<span style= "FONT-SIZE:24PX;" >public Boolean iswificonnected (context context) {    if (context! = null) {          Connectivitymanager Mconnectivitymanager = (connectivitymanager) context       . Getsystemservice (context.connectivity_service);         Networkinfo mwifinetworkinfo = Mconnectivitymanager. Getnetworkinfo (Connectivitymanager.type_wifi); WIFI        if (mwifinetworkinfo! = null) {           return mwifinetworkinfo.isavailable ();}       }       return false; } </span>
3) Determine if the mobile network is available

<span style= "FONT-SIZE:24PX;" >public Boolean ismobileconnected (context context) {     if (context! = null) {        Connectivitymanager Mconnectivitymanager = (connectivitymanager) context. Getsystemservice (context.connectivity_service);        Networkinfo mmobilenetworkinfo = Mconnectivitymanager. Getnetworkinfo (connectivitymanager.type_mobile);        if (mmobilenetworkinfo! = null) {            return mmobilenetworkinfo.isavailable ();}        }      return false; } </span>
4) Get the type information for the current network connection
<span style= "FONT-SIZE:24PX;" >public static int Getconnectedtype (context context) {      if (context! = null) {         Connectivitymanager Mconnectivitymanager = (connectivitymanager) context. Getsystemservice (context.connectivity_service);          Networkinfo mnetworkinfo = Mconnectivitymanager.getactivenetworkinfo ();         if (mnetworkinfo! = null && mnetworkinfo.isavailable ()) {             return Mnetworkinfo.gettype ();}      }       return-1; } </span>
when developing an Android app, it involves network access and often requires a network status check to provide the user with the necessary reminders. This work can generally be done through Connectivitymanager.

Connectivitymanager has four main tasks:
1. Monitor mobile network status (including Gprs,wifi, UMTS, etc.)
2, when the mobile phone status changes, send broadcast
3. Failover when a network connection fails
4. Provide the application with a high-precision and coarse state that can obtain available networks

When we want to listen to the network status in the program, just a few steps:
1, define a receiver overloaded with the OnReceive function, in which to complete the required functions, such as based on WiFi and GPRS is disconnected to change the appearance of the space

<span style= "FONT-SIZE:24PX;" >onnectionreceiver = new Broadcastreceiver () {@Override public    void OnReceive (context context, Intent Intent) {
   connectivitymanager connectmgr = (connectivitymanager) getsystemservice (connectivity_service);        Networkinfo mobnetinfo = Connectmgr.getnetworkinfo (connectivitymanager.type_mobile);        Networkinfo wifinetinfo = Connectmgr.getnetworkinfo (Connectivitymanager.type_wifi);       if (!mobnetinfo.isconnected () &&!wifinetinfo.isconnected ()) {        log.i (TAG, "Unconnect");        Unconnect network         }else {         //Connect Network         }}     ; </span>
2, register receiver in the appropriate place, you can register in the program, call the following function in OnCreate:
<span style= "FONT-SIZE:24PX;" >intentfilter intentfilter = new Intentfilter (); Intentfilter.addaction (connectivitymanager.connectivity_action); Registerreceiver (Connectionreceiver, Intentfilter); </span>

3, when appropriate to unregister receiver, can be canceled in the program, in the Ondestroye call the following function:
<span style= "FONT-SIZE:24PX;" >if (Connectionreceiver! = null) {   unregisterreceiver (connectionreceiver);} </span>
in the test, you have experienced a situation where a routing device that is currently connected to WiFi is turned off, but the program does not capture the Unconnect network, possibly because the mobile device immediately connects to another routing device.

Android Monitor network status

<span style= "FONT-SIZE:24PX;" >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.CONNECT ED) {           log.i ("Networkstate", "Availabel");           return true    ;     }}} return false; } </span>

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

<span Style= "FONT-SIZE:24PX;"    > @Override public void onreceive (context context, Intent Intent) {log.e (TAG, "Network status change");   Boolean success = false;     Get Network connection service 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 being used success = true; } state = Connmanager.getnetworkinfo (connectivitymanager.type_mobile). GetState ();      Gets the network connection status if (state.connected! = state) {//Determines whether the GPRS network is being used success = true;      } if (!success) {Toast.maketext (locationmapactivity.this, "Your network connection is interrupted", Toast.length_long). Show (); }} </span> 
<span style= "FONT-SIZE:24PX;" >/Register Network Monitor Intentfilter filter = new Intentfilter (); Filter.addaction (connectivitymanager.connectivity_action); Registerreceiver (mnetworkstatereceiver, filter); In the activity of the OnDestroy: ' Unregisterreceiver (Mnetworkstatereceiver); Cancel Monitoring </span>
many friends in the Android development, will encounter the phone network type judgment, because on the current Android platform phone: There may be 4 in the state
1. No network (this state may be due to phone downtime, network is not open, bad signal, etc.)
2. Use WiFi internet access
3.CMWAP (China Mobile agent)
4.CMNET Internet access
These four states, if there is no network, must not be able to request the Internet, if it is WAP need to add China Mobile agent for mobile phone, about the mobile phone to add agents!
Here's how the network is judged:

<span style= "FONT-SIZE:24PX;" >public static int Getapntype (context context) {   int netType =-1;    Connectivitymanager connmgr = (connectivitymanager) context.getsystemservice (context.connectivity_service);    Networkinfo networkinfo = Connmgr.getactivenetworkinfo ();    if (networkinfo==null) {      return netType;     }    int nType = Networkinfo.gettype ();    if (ntype==connectivitymanager.type_mobile) {      log.e ("Networkinfo.getextrainfo ()", "Networkinfo.getextrainfo () Is "+networkinfo.getextrainfo ());    if (Networkinfo.getextrainfo (). toLowerCase (). Equals ("Cmnet")) {           netType = cmnet;      }    else{           netType = Cmwap;     }     }    else if (Ntype==connectivitymanager.type_wifi) {           netType = WIFI;     }     return netType; } </span>




Android Check network status step

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.