Android uses Broadcastreceiver to monitor network status

Source: Internet
Author: User

In the development, often encounter the need to judge the status of mobile network to carry out a variety of functions, here is a brief introduction of the implementation of this feature.

Title, through Broadcastreceiver we can hear it when the network state changes.

So, there are two ways to register a broadcast:

1. Static registration: Register with the label declaration in Androidmanifest.xml, and set the filter in the label.

<!--inherit Broadcastreceiver, override Onreceiver method--><receiver android:name= "Myrecevice" > <intent-filter> <!--use filters to receive the specified action broadcast--<action android:name= "com.dragon.net" ></action> </intent-filter ></receiver>

2. Dynamic registration:

Intentfilter intentfilter = new Intentfilter (); intentfilter.addaction (String); Specifies an action for the broadcastreceiver to be used to receive the broadcast Registerreceiver (broadcastreceiver,intentfilter) of the same action;

Manual removal required when not in use

Unregisterreceiver (Broadcastreceiver);

The difference between the two:

    1. Static broadcast is a resident broadcast, and if there is a broadcast message after closing the program, the program will be automatically run by the system call. Dynamic broadcasts follow the activity life cycle.

    2. When the broadcast is an orderly broadcast:

      1. High priority first receive.

      2. Same priority, dynamic takes precedence over static.

    3. Ignore priority when broadcasting as a normal broadcast, dynamic takes precedence over static


We are registering with dynamic broadcast this time

First, add permissions to the project, which is a must. Many times it's easy to forget

<!--access network permissions--><uses-permission android:name= "Android.permission.INTERNET"/><!--Detect network State permissions-->< Uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>

The code is affixed:

Detect network Connection Status private connectivitymanager manager; @Overrideprotected  void oncreate (Bundle  savedinstancestate)  {    super.oncreate (savedinstancestate);     setcontentview (r.layout.activity_main);     intentfilter intentfilter =  new intentfilter ();     intentfilter.addaction (connectivitymanager.connectivity_ ACTION);     registerreceiver (Networkreceiver, intentfilter);} Private broadcastreceiver networkreceiver = new broadcastreceiver ()  {      @Override     public void onreceive (context context,  intent intent)  {        if  (networkavailable ())              networkstate ();         else    &nbsP;       toast.maketext (mainactivity.this,  "Please check the network environment",  Toast.length_short). Show ();    }}; @Overrideprotected  void ondestroy ()  {     super.ondestroy ();     unregisterreceiver (NetworkReceiver);} /** *  detect if the network is connected  */private boolean networkavailable ()  {    try  {        thread.sleep (;      )   //Get network connection Information         manager =  (Connectivitymanager )  getsystemservice (Context.connectivity_service);        if  (manager != null)  {            //   Get Networkinfo Objects             NetworkInfo  Networkinfo = manager.getActivenetworkinfo ();             //to determine if the network is connected             if  (networkinfo != null  | |  networkinfo.isavailable ())  {                 return true;             }        }    } catch  ( exception e)  {        e.printstacktrace ();     }    return false;} /** *  Network has been connected, then to determine whether it is a WiFi connection or mobile connection  */private void networkstate ()  {     networkinfo.state mobile = manager.getnetworkinfo (ConnectivityManager.TYPE_MOBILE). GetState ();     networkinfo.state wifi = manageR.getnetworkinfo (Connectivitymanager.type_wifi). GetState ();    if  (mobile ==  networkinfo.state.connected | |  mobile == networkinfo.state.connecting)  {         Toast.maketext (this,  "Current network status for Mobile",  toast.length_short). Show ();    }     //judge for WiFi status only load ads, if it is GPRS mobile network does not load!     if  (wifi == networkinfo.state.connected | |  wifi == networkinfo.state.connecting)  {         Toast.maketext (this,  "Current network status is Wi-Fi",  toast.length_short). Show ();     }}

In the Wi-Fi status switch to the mobile state there will be a gap is no network, so need to let the program sleep 0.6 seconds to let the program only display mobile toast, the time depends on the phone.


So. SOURCE Stacking here: http://down.51cto.com/data/2225418


If you like my article, please pay attention to me.

This article is from the "Android Development column" blog, be sure to keep this source http://liuyvhao.blog.51cto.com/11690759/1793315

Android uses Broadcastreceiver to monitor network status

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.