Check Internet Connection Code Snippet For Android Studio

 

Welcome. In this tutorial you will learn how to check for Active Internet Connection in your Android Devices.

Android Internet Connectivity Check Example

When we are creating android apps that require internet access, then it is a good habit to first check for Internet Access. So to check whether your Android device has  an active Internet Connection or not, you can use this code snippet given below.

 

We will have to use ConnectivityManager for this purpose. Connectivity manager is used to manage and monitor active connections (WIFI, Mobile Data, etc) and send broadcast intents when network connectivity changes. It has various functions for several different purposes. The function getActiveNetworkInfo returns details about the currently active default data network. One should always check networkInfo isConnected before initiating any kind of network traffic. This may return a null value when there is no network available.However you should note that using this function is deprecated in API level 29, so take that in mind before using this for creating apps for API level 29 or above.

The above code stated here will return true if the device has active internet connection else it will return false. You can use this function anywhere while creating your app.  Just call the above function from anywhere and check for true or false.

Also note that the above code will require Internet so you will have to first modify the AndroidManifests file and add the following code to it:

<uses-permission android:name="android.permission.INTERNET" />

 

The image below gives an example  for checking internet connection in Android When the button is pressed, it will check for internet and display it as Toast.

Check Internet code snippet for android studio example

 

The Complete Code Snippet for above example is given below:-

Java (MainActivity.java)

XML (activity_main.xml)

 

You can directly copy paste these snippets to your android studio, and they should work perfectly. Just save and run your project.

For a more detailed guide, you can also visit android’s official guide below:-

https://developer.android.com/reference/android/net/ConnectivityManager

Comment down below if you are facing any problems.

 

Also Read:-

Add a Comment

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