How to Obtain the Connection Information Programmatically in Android?
Last Updated :
14 Oct, 2020
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 implemented an application through which the details regarding the current network could be fetched easily and available in one place. The information or the entities regarding the connection that we extracted from the device in our program were:
- IP Address: It is a numerical label delegated to every device connected that is connected to a network that uses the Internet Protocol for communication.
- Link Speed: It is the maximum achievable speed (in Bits per second) that the device can communicate with the other on the same network.
- Network ID: It is the portion of an IP address on which a host resides. It identifies the TCP/IP network
- SSID (Service Set Identifier): is a unique ID consisting of 32 characters that are used for wireless network naming.
- Hidden SSID: Same as SSID. Hiding the SSID an efficient way of securing the network. This prevents the network from showing up in the list of available Wi-Fi networks when people scan for nearby Wi-Fi connections.
- BSSID: The SSID keeps the packets within the correct WLAN. The packets are safe even when overlapping WLANs are present. Nevertheless, there are multiple access points within every WLAN. Basic Service Set Identifier (BSSID) identifies those access points and the associated clients and is included in all wireless packets.
Unfortunately, a few entities, such as the MAC Address, could not be fetched correctly, and there is a genuine reason.
- MAC addresses are globally unique, which makes every other device unique from the other. This label is not user-resettable and survives factory resets. Therefore, it is not preferred to identify the users uniquely.
- From Android 6.0 (API 23) and Android 9 (API 28), local device MAC addresses, such as Bluetooth and Wi-Fi, are not available through the third-party APIs.
- The WifiInfo.getMacAddress() method and the BluetoothAdapter.getDefaultAdapter().getAddress() method both by default return 02:00:00:00:00:00.
- Additionally, between Android 6 and Android 9, the following permissions must be held to access MAC addresses of nearby external devices which are available through Bluetooth and Wi-Fi scans:
- Method/Property Permissions Required: ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
Approach
To obtain the current connection information in Android, we shall follow the following steps. Note that we are going to implement this project using the Kotlin language.
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_WIFI_STATE, ACCESS-FINE-LOCATION, and ACCESS_COARSE_LOCATION.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Below is the completed 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 these permissions-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<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">
<!--A TextView to display all the fetched information-->
<TextView
android:id="@+id/wifiInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</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.annotation.SuppressLint
import android.content.Context
import android.net.wifi.WifiManager
import android.os.Bundle
import android.text.format.Formatter
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Invoking the Wifi Manager
val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
// Method to get the current connection info
val wInfo = wifiManager.connectionInfo
// Extracting the information from the received connection info
val ipAddress = Formatter.formatIpAddress(wInfo.ipAddress)
val linkSpeed = wInfo.linkSpeed
val networkID = wInfo.networkId
val ssid = wInfo.ssid
val hssid = wInfo.hiddenSSID
val bssid = wInfo.bssid
// Finding the textView from the layout file
val wifiInformationTv = findViewById<TextView>(R.id.wifiInfo)
// Setting the text inside the textView with
// various entities of the connection
wifiInformationTv.text =
"IP Address:\t$ipAddress\n" +
"Link Speed:\t$linkSpeed\n" +
"Network ID:\t$networkID\n" +
"SSID:\t$ssid\n" +
"Hidden SSID:\t$hssid\n" +
"BSSID:\t$bssid\n"
}
}
Output: Run on Emulator
Note: The following program requires the device to have an active connection. Kindly connect to Wi-Fi. Failing to do so would fetch nothing.
Similar Reads
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 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
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 notice
4 min read
How to Check GPS is On or Off in Android Programmatically?
GPS (Global Positioning System) is a satellite-based navigation system that accommodates radio signals between satellite and device to process the device's location in the form of coordinates. GPS gives latitude and longitude values of the device. Recent mobile phones are equipped with GPS modules t
2 min read
How to Get the Connection Information in Android using Jetpack Compose?
Many times while building an android application we require connection-related information about the android device such as IP address, link speed, and others within our android application. In this article, we will take a look at How to obtain connection-related information in the android applicati
4 min read
How to Get the MAC of an Android Device Programmatically?
MAC stands for Media Access Control. The MAC address is also known as the Equipment Id Number. This MAC Address is provided by the Network Interface Card. In this article, we will see step by step from creating a new empty project to How to make an android app to display MAC Address using Java. Note
2 min read
How to Get the Device's IMEI and ESN Programmatically in Android?
Many times while building Android Applications we require a unique identifier to identify the specific mobile users. For identifying that user we use a unique address or identity. For generating that unique identity we can use the android device id. In this article, we will take a look at How to get
4 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 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
How to Check Airplane Mode State in Android Programmatically?
Airplane Mode is often seen in action during flights, avoiding calls, or rebooting the network on mobiles, tablets, and laptops. Airplane mode is a standalone mode where the device turns down the radio communications. These may include Wifi, GPS, Telephone Network, Hotspot depending upon the year of
3 min read