Use broadcast to update network status changes in real time

Source: Internet
Author: User

If the network is suddenly disconnected, we should promptly remind the user that the network has been disconnected. To achieve this function, we can receive a broadcast that the network status has changed from the connection status to the disconnected status, the system will send a broadcast. After receiving the broadcast, we can perform corresponding operations through the network status.

Public class networkstatereceiver extends broadcastreceiver {

@ Override

Public void onreceive (context, intent ){

If (! Isnetworkavailable (context )){

// Network unavailable operation

} Else {

// Available network operations

}

}


/**

* Whether the Network is available

*

*/

Public static Boolean isnetworkavailable (context ){

Connectivitymanager Mgr = (connectivitymanager) Context. getsystemservice (context. connectivity_service );

Networkinfo [] info = Mgr. getallnetworkinfo ();

If (info! = NULL ){

For (INT I = 0; I <info. length; I ++ ){

If (info [I]. getstate () = networkinfo. state. Connected ){

Return true;

}

}

}

Return false;

}

}


Register the receiver information again:


<Cycler Android: Name = ". networkstatereceiver">

<Intent-filter>

<Action Android: Name = "android.net. Conn. connectivity_change"/>

<Category Android: Name = "android. Intent. Category. Default"/>

</Intent-filter>

</Cycler>

You must also add the following network restrictions:

<Uses-Permission Android: Name = "android. Permission. access_network_state"/>


Use broadcast to update network status changes in real time

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.