Android programs a way to determine whether a network connection is available

  • 2020-11-26 18:58:49
  • OfStack

This article gives an example of how Android can program to determine whether a network connection is available. To share for your reference, the details are as follows:

In order to improve the user experience, the first step we need to take when developing android application is to get data from the Internet:

1. Determine if your phone is currently connected to the Internet

2. Whether the Internet is enabled or not

Then to execute the network logic, to avoid not networking to do unnecessary work!

This is how we usually judge


public static boolean isNetAvailable(Context context) { 
  ConnectivityManager connectManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
  return (connectManager.getActiveNetworkInfo() != null); 
} 

But this only completes the first step, which is to determine whether the network is on or not,

Note: Turning it on does not mean you can access the Internet,

There are 1 ways to observe NetworkInfo:

NetworkInfo.isAvailable()

The official explanation is that

Indicates whether network connectivity is possible. A network is unavailable when a persistent or semi-persistent condition prevents the possibility of connecting to that network. Examples include
The device is out of the coverage area for any network of this type.
The device is on a network other than the home network (i.e., roaming), and data roaming has been disabled.
The device's radio is turned off, e.g., because airplane mode is enabled.
Returns:
true if the network is available, false otherwise

He listed several cases where the Internet was connected but not available,

So let's change it this way:


public static boolean isNetAvailable(Context context) {
  ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo info = manager.getActiveNetworkInfo();
  return (info != null && info.isAvailable());
}

I hope this article has been helpful for Android programming.


Related articles: