A method in Android that listens to determine the state of a network connection

  • 2020-06-01 11:00:53
  • OfStack

There is no need to connect to the server when there is no network or network speed difference.
You can use ConnectivityManager to determine whether you are connected to the network and what type of network you are using.

Determine if there is a network connection

The following code USES the ConnectivityManager query to determine if an Internet connection is active.


ConnectivityManager cm =
        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
 
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                      activeNetwork.isConnectedOrConnecting();

Determine the Internet connection type

The connection type might be moving data, WiMax,WIFI, Ethernet. The network type can be queried in a manner similar to the following:

boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;

Moving data consumes more power than WIFI, so be aware. Downloading large files should be delayed until wifi is available.

Listen for connection changes

ConnectivityManager will change when the connection is sending radio "android. net. conn. CONNECTIVITY_CHANGE", so, registration, listening 1 under the radio can:

<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>

This is triggered every time the data is moved between WIFI and WIFI, and this change can be quite frequent. It is best to listen to the broadcast only when you have previously paused the download or update. Usually check your network connection once before downloading or updating it.
In the next video, we'll switch to the receiver that the switch declares in manifest.


Related articles: