Android broadcast monitoring network status
When we are doing multi-thread downloads, or when loading the h5 interface, we often encounter poor network status or disconnection of the network. Here or when our application starts and does not exit, we need to judge the network status monitoring.
At this time, we usually handle it in two ways.
First: Turn on the service.
Second: the form of sending broadcasts.
Method 2 is recommended.
The source code is as follows:
broadcast:
/** * Internet broadcast */ BroadcastReceiver connectionReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connectMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo mobNetInfo = (ConnectivityManager.TYPE_MOBILE); NetworkInfo wifiNetInfo = (ConnectivityManager.TYPE_WIFI); if (!() && !()) { ("yuyahao", "The Internet is out of order"); Message msg = new Message(); = ; (msg); // unconnect network }else { // connect network (TAG, "I'm here to visit"); } } };
register:
// When there is a network, register to listen to the broadcast on the Internet. IntentFilter intentFilter = new IntentFilter(); (ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(connectionReceiver, intentFilter); showDialog(); (mUpdateUIThread);
The complete code is as follows:
Method 1 is to enable service. The code is very simple.
Thank you for reading, I hope it can help you. Thank you for your support for this site!