How to check internet connection in android programmatically

Answer 1. 

Whenever we need connectivity in an app, it is a good practice to check that we have it available before requesting any operation and wait for a timeout or similar error. For this you have to use ConnectivityManager and NetworkInfo , I always use the following snippet:

1. private boolean isNetworkConnected(Context context) {

2.  ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context

3.    CONNECTIVITY_SERVICE);

4. NetworkInfo info = connectivityManager.getActiveNetworkInfo();

5. if (info == null || !info.isConnected() || !info.isAvailable()) {

6.    return false;

7. }

8. return true;

9. }

For this code to work, you need a special permission to access the network state, with the permission to use the Internet connection (“android.permission.INTERNET”) is not enough:

<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />  

The above code is very basic, and if necessary you can get more information about the active connection through the getType () method and know the type of connection using some of the constants defined in ConnectivityManager:

info.getType () -> ConnectivityManager.TYPE_MOBILE, ConnectivityManager.TYPE_WIFI, ConnectivityManager.TYPE_WIMAX…

If we make intensive use of data, it may be necessary to give the user the possibility of configuring the application so that it only uses the Internet connection via WIFI, or to notify them of this situation due to the economic cost that it could entail. Likewise, in the case that the connection is of a mobile type, we can also find out exactly its type with the constants defined in TelephonyManager :

info.getSubtype () -> TelephonyManager.NETWORK_TYPE_UMTS, TelephonyManager.NETWORK_TYPE_LTE, TelephonyManager.NETWORK_TYPE_GPRS …

Answer 2.

There are times when our applications need internet access. If the user does not have the connection available, it is very likely that the application fails or does not do exactly what we want. Otherwise, the situation may arise that the user is connected to the data network and, if the application requires downloading large information from the Internet, the user’s data would be consumed. So that he is always notified and knows what is happening at all times, you have to go ahead and take these details into account.

Therefore, in today’s tutorial we will check if the mobile device has internet access and if it does, we will check what type of connection it has, whether it is Wifi or data.

one

Hope the above article is informative. To get more tutorials like this please visit us on our official web page.

Leave a Comment

Your email address will not be published. Required fields are marked *