Current Internet Connection Type in Real-Time Programmatically in Android
Last Updated :
14 Aug, 2024
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.
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"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
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:android="http://schemas.android.com/apk/res/android"
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.
Similar Reads
How to Obtain the Connection Information Programmatically in Android?
Sometimes it becomes challenging to find the network-related details, especially the device's IP address, which could be needed to grant unique preferences through the modem software. Because of the variance in the information shown to the user across multiple Android devices (Samsung, Mi, Lava), we
4 min read
Android Jetpack Compose - Display Current Internet Connection Type
Many times in android applications it is mandatory to check the user's mobile connectivity to the internet whether it may be through mobile data or using Wi-Fi so that the app will work fine with different internet connectivity sources. In this article, we will be building a simple application in wh
3 min read
How to Change Input Type of EditText Programmatically in Android?
EditText in Android UI or applications is an input field, that is used to give input text to the application. This input text can be of multiple types like text (Characters), number (Integers), etc. These fields can be used to take text input from the users to perform any desired operation. Let us s
3 min read
Programmatically Check the Network Speed in Android
Network speed can be defined as the total number of packets being exchanged by the client and the server per second, usually calculated in Megabits per second(Mbps). A bit is either a 0 or 1. 1 Megabit implies 1 Million bits. Usually, packet size depends on the protocol and various other factors and
6 min read
How to Detect Tablet or Phone in Android Programmatically?
A Mobile is a portable electronic device that allows you to make calls, send messages, and access the internet, among other functions. A tablet is a mobile computing device with a touchscreen display and typically a larger screen size than a smartphone. Both devices are designed to be portable and a
3 min read
How to Get RAM Memory in Android Programmatically?
RAM (Random Access Memory) of a device is a system that is used to store data or information for immediate use by any application that runs on the device. Every electronic device that runs a program as a part of its application has some amount of RAM associated with it. Mobile devices nowadays come
3 min read
How to Get Internal Memory Storage Space in Android Programmatically?
Every device has an internal memory where it can store files and applications. The internal memory of devices can vary anywhere between 4 GB to 512GB. As internal memory gets filled up with a stack of files and applications, the available space decreases. Developers, to save internal memory, design
3 min read
How to Check the Type of Charging (USB/AC) in Android Programmatically?
When altering the frequency of the background updates to scale back the effect of these updates on battery life, checking the present battery level and charging state is a superb place to start. The battery-life impact of performing application updates depends on the battery level and charging state
3 min read
How to Find Out Carrier's Name in Android Programmatically?
In this article we will see how to retrieve the carrier name on Android device. This information can be useful for applications that need to provide specific functionality based on the user's cellular network provider. A sample video is given below to get an idea about what we are going to do in thi
3 min read
How to Check if the Battery is Charging or Not in Android Programmatically?
The charging status can change as quickly as a device can be plugged in, so it's crucial to monitor the charging state for changes and alter your refresh rate accordingly. The Battery Manager broadcasts an action whenever the device is connected or disconnected from power. It is important to receive
3 min read