Some Android applications have two connection modes: "network" and "Network disconnection". "Network disconnection" and "Network disconnection" have two different interfaces, network disconnection API is called when the network is disconnected, and network-connected API is called when the network is connected. If the network-connected API is called when the network is disconnected, an exception occurs. If the network is disconnected, you should switch to the "disconnected" interface and call the API in the case of "disconnected.
1. To detect the network, you must first have the following permissions (access to the network and access to the network status ):
<Uses-Permission Android: Name = "android. Permission. Internet"/>
<Uses-Permission Android: Name = "android. Permission. access_network_state"/>
2. Configure the broadcasted er in manifest to monitor the network disconnection. In the action, the operator is triggered when the network connection changes, as shown below:
<Cycler
Android: Name = ". connectionchangereceiver"
Android: Label = "networkconnection">
<Intent-filter>
<Action Android: Name = "android.net. Conn. connectivity_change"/>
</Intent-filter>
</Cycler>
3. The broadcastreceiver implementation code is as follows:
Public class connectionchangereceiver extends broadcastreceiver {
@ Override
Public void onreceive (context, intent ){
Connectivitymanager connectivity = (connectivitymanager) Context
. Getsystemservice (context. connectivity_service );
If (connectivity! = NULL ){
Networkinfo [] info = connectivity. getallnetworkinfo ();
If (info! = NULL ){
For (INT I = 0; I <info. length; I ++ ){
If (info [I]. getstate () = networkinfo. state. Connected ){
// Exit directly if there is a network connection
Return;
}
}
}
}
// If there is no network connection (the network has been disconnected), take the corresponding logic and jump to the corresponding interface.
Sharedpreferences settings = context. getsharedpreferences (
Constant. prefs_name, context. mode_private );
Sharedpreferences. Editor editor = settings. Edit ();
Editor. putboolean (constant. prefs_network_online, false );
Editor. Commit ();
Intent. setclass (context, networklistactivity. Class );
// Set the flag_activity_new_task flag when you start the activity in broadcastreceiver (or android components without interfaces like the service.
// Clear all the activities and set the flag_activity_clear_top flag.
Intent. setflags (intent. flag_activity_clear_top | intent. flag_activity_new_task );
Context. startactivity (intent );
}
Hope to help you!