A method for monitoring the status of network connections in Android _android

Source: Internet
Author: User

There is no need to connect to the server in the absence of a net or poor network speed.
You can use Connectivitymanager to determine whether you are connected to the network and the type of network.

Determine if there is a network connection

The following code uses a Connectivitymanager query to determine whether there is an Internet connection or an active network connection.

Copy Code code as follows:

Connectivitymanager cm =
(Connectivitymanager) Context.getsystemservice (Context.connectivity_service);

Networkinfo activenetwork = Cm.getactivenetworkinfo ();
Boolean isconnected = activenetwork!= null &&
Activenetwork.isconnectedorconnecting ();

To determine the type of Internet connection

The connection type may be mobile data, Wimax,wifi, Ethernet. You can query the network type by using a method similar to the following:

Copy Code code as follows:
Boolean iswifi = Activenetwork.gettype () = = Connectivitymanager.type_wifi;

Mobile data than WiFi power consumption, should be noted. Download large files should be delayed until there is wifi.

Monitor connection changes

Connectivitymanager will send a broadcast "Android.net.conn.CONNECTIVITY_CHANGE" When the connection changes, so register and listen to this broadcast to:

Copy Code code as follows:
<action android:name= "Android.net.conn.CONNECTIVITY_CHANGE"/>

Each time it changes from moving data to WiFi, the change can be frequent. It's best to listen to this broadcast only when you pause the download or update. You typically check your network connection before downloading or updating.
The following section tells the receiver that the toggle switch is declared in the manifest.

Related Article

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.