Android Network connection judgment and processing

Source: Internet
Author: User

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

<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>

1) Determine if there is an Internet connection

1  Public Boolean isnetworkconnected (Context context) {    2     ifnull) {    3         Connectivitymanager Mconnectivitymanager = (connectivitymanager) context    4                 . Getsystemservice (Context.connectivity_service);   5         Networkinfo mnetworkinfo = mconnectivitymanager.getactivenetworkinfo ();   6         if NULL ) {    7             return  mnetworkinfo.isavailable ();   8         }    9    }       returnfalse ;    One}  

2) determine if the WiFi network is available

  1   public   boolean   iswificonnected (context context) {  2   if  (context! =  null  ) {  3  connectivitymanager mCo Nnectivitymanager =  (connectivitymanager) context   4  . Getsystemservice (Co ntext.  Connectivity_service);                  5  networkinfo mwifinetworkinfo =  mconnectivitymanager   6    . Getnetworkinfo (Connectivitymanager.type_wifi);               7   if  (mwifinetworkinfo! =  null  ) {  8   return    mwifinetworkinfo.isavailable ();    9  }   ten  }   one   return   false   ;   } 

3) Determine if the mobile network is available

  1   public   boolean   ismobileconnected (context context) {  2   if  (context! =  null  ) {  3  Connectivityman Ager Mconnectivitymanager =  (connectivitymanager) context   4  . Getsystemse  Rvice (Context.connectivity_service);                  5  networkinfo mmobilenetworkinfo =  mconnectivitymanager   6    . Getnetworkinfo (Connectivitymanager.type_mobile);               7   if  (mmobilenetworkinfo! =  null  ) {  8   return    mmobilenetworkinfo.isavailable ();    9  }   ten  }   one   return   false   ;   } 

4) Get the type information for the current network connection

1  Public Static int Getconnectedtype (Context context) {    2     ifnull) {    3         Connectivitymanager Mconnectivitymanager = (connectivitymanager) context    4                 . Getsystemservice (Context.connectivity_service);   5         Networkinfo mnetworkinfo = mconnectivitymanager.getactivenetworkinfo ();   6         if null && mnetworkinfo.isavailable ()) {    7             return  Mnetworkinfo.gettype ();   8         }    9    }       return -1;    One}  

When developing an Android app, it involves network access, often requiring network status checks to provide users 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

New Broadcastreceiver () {      @Override   publicvoid  onreceive (context context, Intent Intent) {    = (Connectivitymanager) Getsystemservice (connectivity_service);     = Connectmgr.getnetworkinfo (connectivitymanager.type_mobile);     = Connectmgr.getnetworkinfo (connectivitymanager.type_wifi);     if (!mobnetinfo.isconnected () &&! wifinetinfo.isconnected ()) {     "unconnect");      // unconnect network     } Else {    //  Connect Network}}}  ;

2, register receiver in the appropriate place, you can register in the program, call the following function in OnCreate:

New Intentfilter ();  Intentfilter.addaction (connectivitymanager.connectivity_action);  Registerreceiver (Connectionreceiver, intentfilter);

3, when appropriate to unregister receiver, can be canceled in the program, in the Ondestroye call the following function:

if NULL ) {   unregisterreceiver (connectionreceiver);  }

Ps: There are a lot of ways to use Telephonymanager on the Internet, the method is as follows (but I have tried several times have problems, such as each time the first time into an activity will automatically receive the network disconnection signal, each time the network state changes to receive multiple callbacks and the status is incorrect. Do not know what to pay attention to the place, seek guidance! )

Final Telephonymanager mtelephonymgr = (Telephonymanager) Getsystemservice (context.telephony_service);  Mtelephonymgr.listen (new  Phonestatelistener () {@Overridepublicvoid Ondataconnectionstatechanged (int.  ) {switch(state) { case telephonymanager.data_disconnected:// network disconnect break ;  Case Telephonymanager.data_connecting:// Network is connecting break;  Case telephonymanager.data_connected:// network connection on break;}}, Phonestatelistener.listen_data_connection_state);

As for the second method, I have not tried it. The first way is still relatively good, if you want to hide the program in the background, it is recommended to open a service, the Broadcastreceiver registered in the service, but do not forget to unregister.

In the test, 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 is immediately connected to another routing device.

Android Monitor network status
1  Public Static Booleanisnetworkavailable (Context context) {2Connectivitymanager connectivity =(Connectivitymanager) Context.getsystemservice (Context.connectivity_service); 3         if(Connectivity = =NULL) {   4LOG.I ("Networkstate", "Unavailabel"); 5             return false; 6}Else {   7Networkinfo[] Info =Connectivity.getallnetworkinfo (); 8             if(Info! =NULL) {   9                  for(inti = 0; i < info.length; i++) {   Ten                     if(info[i].getstate () = =NetworkInfo.State.CONNECTED) { OneLOG.I ("Networkstate", "Availabel");  A                         return true;  -                     }    -                 }    the             }    -         }    -         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:

1 @Override2  Public voidOnReceive (Context context, Intent Intent) {3LOG.E (TAG, "Network status change"); 4   5 BooleanSuccess =false; 6   7 //access to network connectivity Services8Connectivitymanager Connmanager =(Connectivitymanager) Getsystemservice (Connectivity_service); 9 //State state = Connmanager.getactivenetworkinfo (). GetState (); Tenstate State =Connmanager.getnetworkinfo ( OneConnectivitymanager.type_wifi). GetState ();//Get network Connection Status A if(state.connected = = state) {//determine if a WiFi network is being used -Success =true;  - }    the    -State =Connmanager.getnetworkinfo ( -Connectivitymanager.type_mobile). GetState ();//Get network Connection Status - if(state.connected! = State) {//determine if the GPRS network is being used +Success =true;  - }    +    A if(!success) {    atToast.maketext (locationmapactivity. This, "Your network connection has been interrupted", Toast.length_long). Show ();  - }     -    -}


In the OnCreate of activity:

// Register for Network   monitoring New Intentfilter ();    Filter.addaction (connectivitymanager.connectivity_action);   Registerreceiver (mnetworkstatereceiver, filter);    // In the OnDestroy of activity: '      //

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 phones, for mobile phones to add agents, please go to

Http://www.2cto.com/kf/201111/112100.html Here is an example of adding China Mobile agent!

Here's how the network is judged:

1 /**2 3      * @authorSky4 5 * Email [email protected]6 7 * qq:8409501058 9 * Get current network status-1: No network 1:wifi network 2:wap network 3:net NetworkTen  One      * @paramContext A  -      * @return -  the      */  -  -      Public Static intGetapntype (Context context) { -  +         intNetType =-1;  -  +Connectivitymanager connmgr =(Connectivitymanager) Context.getsystemservice (context.connectivity_service); A  atNetworkinfo Networkinfo =connmgr.getactivenetworkinfo (); -  -           -  -         if(networkinfo==NULL){  -  in             returnNetType; -  to         }  +  -         intNType =Networkinfo.gettype (); the  *         if(ntype==connectivitymanager.type_mobile) {  $ Panax NotoginsengLOG.E ("Networkinfo.getextrainfo ()", "Networkinfo.getextrainfo () is" +networkinfo.getextrainfo ());  -  the             if(Networkinfo.getextrainfo (). toLowerCase (). Equals ("Cmnet")){  +  ANetType =CMNET; the  +             }  -  $             Else{  $  -NetType =Cmwap; -  the             }  - Wuyi         }  the  -         Else if(ntype==Connectivitymanager.type_wifi) {  Wu  -NetType =WIFI; About  $         }  -  -         returnNetType; -  A}

Because the access is the service object, so this network state is always refreshed, so we just need to get the network state on it!

Learning is to accumulate, hope to share with you

Original: http://www.cnblogs.com/qingblog/archive/2012/07/19/2598983.html

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.