October 7, 2020

Android WiFi manager with Example

By Mohit Agrawal

Getting started with Android WIFI manager

Introduction

In this android tutorial, I will show you the basics of the android WiFi manager class. First, we will see what is it, and then we will develop an android app that can turn on or turn off the Wifi connection.

What is Android WiFi manager class?

It is an API to access and control the WIFI device connected to your smart phone. Using this API you can get any information like IP address, negotiation state, other network information. You can also scan, add, save, terminate, and initiate Wi-Fi connections.

Using this WIFI manager API we can do following operations:

  • It can scan for the available Wi-Fi networks within the range
  • Allow devices to connect to the internet
  • It can connect to other devices using service discovery
  • Manage a list of configured networks.
  • Manage multiple connections

Set permissions for WiFi manager API

In order to use it, we need to give a few sets of permissions in the android manifest file. The permissions are CHANGE_WIFI_STATEACCESS_WIFI_STATE, and INTERNET.

<manifest ... >
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
...

</manifest>

Android WifiManager class

Android provides us WifiManager class, using this we can perform Wi-Fi-related activities in our applications. This class will provide the required API’s to manage all aspects of Wi-Fi connectivity.

We can instantiate this class by calling the getSystemService method. Check the below code snippet.

WifiManager wmgr = (WifiManager)Context.getSystemService(Context.WIFI_SERVICE);

If you are getting Null value for wmgr, then it means the device does not support Wi-Fi and we can disable all Wi-Fi features.

Here are the few important methods from the WifiManager class:

  • addNetwork(WifiConfiguration config) It adds a new network description to the set of configured networks.
  • createWifiLock(String tag) It creates a new WifiLock.
  • disconnect() This method disassociates from the currently active access point.
  • enableNetwork(int netId, boolean disableOthers) It allows a previously configured network to be associated with
  • getWifiState() This method gets the Wi-Fi enabled state
  • isWifiEnabled() It returns whether Wi-Fi is enabled or disabled.
  • setWifiEnabled(boolean enabled) This method enables or disables Wi-Fi.
  • updateNetwork(WifiConfiguration config) This method updates the network description of an existing configured network.

Using WifiManager get the list of available WiFi connections

Let’s see how we can use the WifiManager class to the list of available wifi networks.

We will the method getScanResults(). It scans and the array of all the available wifi networks in the range.

WifiManager wmgr = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
// Get List of Available Wifi Networks
List<ScanResult> availNetworks = wmgr.getScanResults();
if (availNetworks.size() > 0) {
    String wifis[] = new String[availNetworks.size()];
    // Get Each network detail
    for (int i=0; i<availNetworks.size();i++) {
        wifis[i] = availNetworks.get(i).toString();
    }
}

Example to turn ON / OFF the wifi using WifiManager

STEP-1: Create a new android project and name it WifiManagerDemo.

STEP-2: Go to android manifest file and give the required permissions.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="xyz.warmodroid.wifimanager">
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_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: Go to the activity_main.xml and create two buttons to turn ON and turn OFF the wifi.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="10dp"
    android:paddingRight="10dp">
    <Button
        android:id="@+id/buttonOn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Wifi Turn On" android:layout_marginLeft="70dp" android:layout_marginTop="200dp" />
    <Button
        android:id="@+id/buttonOFF"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/buttonOn"
        android:layout_toRightOf="@+id/buttonOn"
        android:text="Wifi Turn OFF" />
</RelativeLayout>
wifi manager android 1

STEP-4: Now let’s write the code. Go to the MainActivity.kt and write the below code.

import android.content.Context
import android.content.Intent
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        buttonOn.setOnClickListener {
            switchWIFI(true)
        }

        buttonOFF.setOnClickListener {
            switchWIFI(false)
        }
    }

    fun switchWIFI(isON: Boolean) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val panelIntent = Intent(Settings.Panel.ACTION_WIFI)
            startActivityForResult(panelIntent, 1);
        } else {
            // if it is Android Q and above go for the newer way
            val wmgr = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
            wmgr.setWifiEnabled(isON)
        }
    }
}

Let me give the explanations of the above code. Basically, I am using the method setWifiEnabled(Boolean) to turn OFF and ON the wifi. But the problem here this method is deprecated for the android Q and above.

The solution for this is to open the Settings panel using the intent as shown the above code.

Now you can run your code and play with WifiManager. If you are facing any issue then please let me know it in the comment section.

wifi manager android 2
wifi manager android 3

Demo

Conclusion

Subscribe YouTube: More tutorials like this

I hope this blog post is useful for you, do let me know your opinion in the comment section below.
I will be happy to see your comments down below 👏.
Thanks for reading!!!