Skip to content
Related Articles

Related Articles

Improve Article

Current Internet Connection Type in Real-Time Programmatically in Android

  • Last Updated : 07 Sep, 2021
Geek Week

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. 

Sample GIF

Approach

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.

XML




<?xml version="1.0" encoding="utf-8"?>
    package="org.geeksforgeeks.connectioninfo">
   
    <!--Add this permission to Access the Network State-->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
   
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

 

 

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.

 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <!--This textView will show the current connection status-->
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Not Connected" />
 
</RelativeLayout>

 

 

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.

 

Kotlin




import android.content.Context
import android.net.ConnectivityManager
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
 
class MainActivity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // Declaring the textView from the layout file
        // This textView will display the type of connection
        // Either WIFI, MOBILE DATA, or Not Connected
        val networkConnectionStatus = findViewById<TextView>(R.id.tv)
 
        // A Thread that will continuously monitor the Connection Type
        Thread(Runnable {
            while (true) {
                // This string is displayed when device is not connected
                // to either of the aforementioned states
                var conStant: String = "Not Connected"
 
                // Invoking the Connectivity Manager
                val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
 
                // Fetching the Network Information
                val netInfo = cm.allNetworkInfo
 
                // Finding if Network Info typeName is WIFI or MOBILE (Constants)
                // If found, the conStant string is supplied WIFI or MOBILE DATA
                // respectively. The supplied data is a Variable
                for (ni in netInfo) {
                    if (ni.typeName.equals("WIFI", ignoreCase = true))
                        if (ni.isConnected) conStant = "WIFI"
                    if (ni.typeName.equals("MOBILE", ignoreCase = true))
                        if (ni.isConnected) conStant = "MOBILE DATA"
                }
 
                // To update the layout elements in real-time, use runOnUiThread method
                // We are setting the text in the TextView as the string conState
                runOnUiThread {
                    networkConnectionStatus.text = conStant
                }
            }
        }).start() // Starting the thread
    }
}

 
 

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.

 

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!



My Personal Notes arrow_drop_up
Recommended Articles
Page :