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.

1234567 <!--继承BroadcastReceiver,重写onReceiver方法--><receiverandroid:name="MyRecevice">    <intent-filter>        <!--  使用过滤器,接收指定action广播-->        <actionandroid:name="com.dragon.net"></action>    </intent-filter></receiver>

2. Dynamic registration:

123 IntentFilter intentFilter = newIntentFilter();intentFilter.addAction(String);   //为BroadcastReceiver指定action,使之用于接收同action的广播registerReceiver(BroadcastReceiver,intentFilter);

Manual removal required when not in use

1 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

1234 <!-- 访问网络权限 --><uses-permissionandroid:name="android.permission.INTERNET" /><!-- 检测网络状态权限 --><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

The code is affixed:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 //检测网络连接状态privateConnectivityManager manager;@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    IntentFilter intentFilter = newIntentFilter();    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);    registerReceiver(NetworkReceiver, intentFilter);}privateBroadcastReceiver NetworkReceiver = newBroadcastReceiver() {    @Override    publicvoidonReceive(Context context, Intent intent) {        if(NetworkAvailable())            NetworkState();        else            Toast.makeText(MainActivity.this, "请检查网络环境", Toast.LENGTH_SHORT).show();    }};@Overrideprotectedvoid onDestroy() {    super.onDestroy();    unregisterReceiver(NetworkReceiver);}/** * 检测网络是否连接 */privatebooleanNetworkAvailable() {    try{        Thread.sleep(600);        //得到网络连接信息        manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);        if (manager != null) {            // 获取NetworkInfo对象            NetworkInfo networkInfo = manager.getActiveNetworkInfo();            //去进行判断网络是否连接            if (networkInfo != null|| networkInfo.isAvailable()) {                returntrue;            }        }    } catch(Exception e) {        e.printStackTrace();    }    returnfalse;}/** * 网络已经连接,然后去判断是wifi连接还是mobile连接 */privatevoidNetworkState() {    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, "当前为网络状态为MOBILE", Toast.LENGTH_SHORT).show();    }    //判断为wifi状态下才加载广告,如果是GPRS手机网络则不加载!    if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {        Toast.makeText(this, "当前为网络状态为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.

Android uses Broadcastreceiver to monitor network status

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.