Android WiFi with Examples

  Keywords : Android wifimanager api will help us to manage all aspects of wifi connectivity such as scan for wifi connections or add and initiate wifi connections

Here we will learn wifi in android with examples and how to use android wifimanager api to manage all wifi connections with examples, android set wifi permissions, android programmatically turn on / off wifi or android enable / disable wifi with examples, android scan and get list of available wifi networks with examples.

Android Wi-Fi

In android, Wi-Fi is a wireless network protocol that allows a devices to connect to the internet or connect wirelessly with other devices to exchange the data.

 

Generally, in android applications by using Wi-Fi API’s we can manage all aspects of WI-FI connectivity, such as scan or search for available networks, add / save / delete Wi-Fi connections and managing the data transfer between devices within the range.

 

By using android Wi-Fi API’s in android applications, we can perform following functionalities.

 

  • Scan for the available Wi-Fi networks within the range
  • Allow devices to connect to the internet
  • Connect to other devices through service discovery
  • Manage list of configured networks.
  • Manage multiple connections

Android Set Wi-Fi Permissions

To use Wi-Fi features in our android applications, we must need to add multiple permissions, such as CHANGE_WIFI_STATE, ACCESS_WIFI_STATE and INTERNET in our manifest file.

 

Following is the example of defining the Bluetooth permissions in android manifest file.

 

<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

In android, we can perform Wi-Fi related activities by using WifiManager class in our applications. This class will provide required API’s to manage all aspects of Wi-Fi connectivity.

 

By using WifiManager class, we can perform the operations that are related to network connectivity. We can instantiate this class by using Context.getSystemService(Class) with the argument WifiManager.class or Context.getSystemService(String) with the argument Context.WIFI_SERVICE.

 

Following is the code snippet to initialize WifiManager class using Context.getSystemService(String) with the argument Context.WIFI_SERVICE.

 

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

If you observe above code snippet, we used getSystemService() method to instantiate a WifiManager class.

 

In case if getSystemService() method returns NULL, then the device does not support Wi-Fi and we can disable all Wi-Fi features.

Android Enable or Disable Wi-Fi

If Wi-Fi is supported but disabled, then isWifiEnabled() method will return false and we can request user to enable Bluetooth without leaving our application by using setWifiEnabled method.

 

Following is the code snippet to enable a Wi-Fi in android application by using setWifiEnabled() method.

 

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

If you observe above code snippet, we used setWifiEnabled(true) method to turn ON or Enable a Wi-Fi in our android application.

 

By using setWifiEnabled(false) method we can Disable or turn OFF a Wi-Fi in android applications.

Android List Wireless Networks

By using WifiManager method getScanResults(), we can get the list of available Wi-Fi network details.

 

Following is the code snippet to get the available Wi-Fi network details in android applications.

 

WifiManager wmgr = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
// Get List of Available Wifi Networs
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();
    }
}

If you observe above code, we are getting the available Wi-Fi network details by using getScanResults() method of WifiManager object.

 

Now we will see how to use WifiManager object to turn ON / OFF or Enable / Disable Wi-Fin in our android applications.

Android Wi-fi Turn ON / OFF Example

Following is the example of turning on or off Wi-Fi on button click in android applications.

 

Create a new android application using android studio and give names as WifiExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

 

Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as shown below.

activity_main.xml

<?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/btnOn"
       
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/btnOFF"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_alignBottom="@+id/btnOn"
       
android:layout_toRightOf="@+id/btnOn"
       
android:text="Wifi Turn OFF" />
</
RelativeLayout>

Now open your main activity file MainActivity.java from \java\com.tutlane.wifiexample path and write the code like as shown below

MainActivity.java

package com.tutlane.wifiexample;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
        Button btntOn = (Button)findViewById(R.id.
btnOn);
        Button btntOff = (Button)findViewById(R.id.
btnOFF);
        btntOn.setOnClickListener(
new View.OnClickListener() {
           
@Override
            
public void onClick(View v) {
                WifiManager wmgr = (WifiManager)getApplicationContext().getSystemService(Context.
WIFI_SERVICE);
                wmgr.setWifiEnabled(
true);
            }
        });
        btntOff.setOnClickListener(
new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
                WifiManager wmgr = (WifiManager)getApplicationContext().getSystemService(Context.
WIFI_SERVICE);
                wmgr.setWifiEnabled(
false);
            }
        });
    }
}

If you observe above code, we used setWifiEnabled() method of WifiManager class to enable or disable a Wi-Fi in our application.

 

As discussed, we need to set Wi-Fi permissions in android manifest file (AndroidManifest.xml) to access Wi-Fi features in android applications. Now open android manifest file (AndroidManifest.xml) and write the code like as shown below

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   
package="com.tutlane.wifiexample">
    <
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>

If you observe above code, we added required Wi-Fi permissions in manifest file to access Wi-Fi features in android applications.

Output of Android Wi-Fi Turn ON / OFF Example

When we run above program in android studio we will get the result like as shown below.

 

Android WiFi Example Result

 

When we click on Turn ON button, the device Wi-Fi get switched ON and when we click on Turn OFF button, the device Wi-Fi get switched OFF.

 

This is how we can Turn ON or OFF Wi-Fi in android applications based on our requirements.