For more information, see: http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
Generally, some scheduled tasks are set during development, such as repeated alarm clocks and scheduled tasks started in the background. However, if our network is not connected, there is no need to start the tasks that need to connect to the network.
We can use connectivitymanager to check whether the network is connected or not.
By changing the connection status of the network, the app behavior is changed accordingly to reduce unnecessary operations and prolong the endurance of the device.
Determine whether there is a network connection
Obviously, if there is no network connection, there is no need to do things that require networking.
The following is an example of checking whether a network connection exists:
Connectivitymanager CM = (connectivitymanager) Context. getsystemservice (context. connectivity_service); networkinfo activenetwork = cm. getactivenetworkinfo (); Boolean isconnected = activenetwork. isconnectedorconnecting ();
Determine the type of the connected network
Generally, devices can be connected to mobile networks, WiMAX, Wi-Fi, and Ethernet. By querying the network type of the current activity, you can do the right thing based on the network bandwidth.
Boolean iswifi = activenetwork. GetType () = connectivitymanager. type_wifi;
Using a mobile network is more costly than Wi-Fi, so in most cases, some data acquisition operations are reduced in a mobile network. Similarly, some operations such as downloading files need to be started only when Wi-Fi is available.
If you have disabled the update operation, you need to listen for network switching. If you have a good network, restart the previously canceled operation.
Monitoring Network Connection Switching
When the network connection is changed, connectivitymanager will broadcast connectivity_action ("android.net. Conn. connectivity_change") action messages.
We need to register a handler with the same action as the following in the manifest file:
<Action Android: Name = "android.net. Conn. connectivity_change"/>
When the network connection of the device changes frequently, the broadcast will be continuously triggered from 3G to wifi. Therefore, the best way to restore them is to pause the update or download to start listening to broadcasts. Generally, it is enough to simply check the Internet connection. Before the update starts, there is no further update.