Current Internet Connection Type in Real-Time Programmatically in Android
In today’s league of Information-Centric Network, the developers need to know the type of web searches by the users over the Internet. To target the audience with specific data, developers need to have and work on ample of entities. One such entity is the connection information. Have you ever noticed Google Play asking you to switch to Wi-Fi while you were on Mobile Data trying to download an App? Ever saw a drop in the quality of online video when you switch from Wi-Fi to mobile data? Ethics says it is essential to monitor every entity being used in all the applications, and the Android is capable of it. The role that Android architecture plays here is to switch you from one type of connection to the other possible one in case of a network failure but doesn’t change the specifications of data being displayed. A developer has to program the application in such a way that the data being consumed is optimized. Through this article, we aim to extend our knowledge of extracting the current connection type and display it in the form of an Android application. We shall use the available methods (no third-party elements) to show the information (Connection Type) changes in real-time. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
To obtain the type current connection (Wi-Fi or Mobile Data) in Android, we shall follow the following steps:
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the AndroidManifest.xml file
Go to the AndroidManifest.xml file and add these uses-permissions: ACCESS_NETWORK_STATE.
<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />
Below is the complete code for the AndroidManifest.xml file.
Step 3: Working with the activity_main.xml file
Now go to the activity_main.xml file which represents the UI of the application, and create a TextView where we would broadcast the information from the MainActivity.kt file. Below is the code for the activity_main.xml file.
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file, and refer the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Output: Run on Physical Device
Note: Having an active network interface does not guarantee you that a particular networked service is available. Network issues, server downtime, low signal, captive portals, content filters, and the like can all prevent your app from reaching a server. For instance, you can’t tell if your app can contact the Twitter server until the application receives a valid response call from the Twitter service.