Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
How to Get the Connection Information in Android using Jetpack Compose?
Next article icon

How to Obtain the Connection Information Programmatically in Android?

Last Updated : 14 Oct, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

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"?>
<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.

Output on the Emulator


Next Article
How to Get the Connection Information in Android using Jetpack Compose?
author
aashaypawar
Improve
Article Tags :
  • Android
  • Kotlin
  • Android Projects

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
    3 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
    3 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences