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