Skip to content
Related Articles

Related Articles

Improve Article

How to Obtain the Connection Information Programmatically in Android?

  • Last Updated : 14 Oct, 2020
Geek Week

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:

  1. 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.
  2. Link Speed: It is the maximum achievable speed (in Bits per second) that the device can communicate with the other on the same network.
  3. Network ID: It is the portion of an IP address on which a host resides. It identifies the TCP/IP network
  4. SSID (Service Set Identifier): is a unique ID consisting of 32 characters that are used for wireless network naming.
  5. 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.
  6. 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"?>
    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: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.

Output on the Emulator

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 :