Android Tutorial-Wifi Manager

Hi all, hope you are having a great time in learning android. In this step by step tutorial, we will learn about wifi connectivity.

WiFi Manager

This class provides API for all aspects of WIFI connectivity. Please visit, https://developer.android.com/reference/android/net/wifi/WifiManager to get more details.

To get change the wifi state and to get the list of available wifi networks, we need to add the permissions in AndroidManifest.xml

<uses-permission android:name=”android.permission.ACCESS_WIFI_STATE”/> <uses-permission android:name=”android.permission.CHANGE_WIFI_STATE”/><uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION”/>

Wifi related operation can be executed with the help of WifiManager class ,

WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

Wifi can be enabled or disabled by setWifiEnable() method which takes Boolean as argument  and is wifi enabled or disabled can be checked by isWifiEnabled method which returns Boolean

if (!wifi.isWifiEnabled()) { wifi.setWifiEnabled(true);}

Scan Wifi and get the List

To show the wifi List we need to add a ListView in our Activity_main.xml and list should be initialised in MainActivity.java.

ListView wifilist = findViewById(R.id.wifiList);

To show the content from the list we will need an Adapter.

ArrayList<String> arrayList = new ArrayList<>();

ArrayAdapter adapter = new

ArrayAdapter(this,android.R.layout.simple_list_item_1,arrayList);

//The arrayList will contain the SSID of the available wifi networks in //String Format

wifilist.setAdapter(adapter);

BroadcastReceiver is used to get list of available wifi networks (ScanResults) and the list will be stored in the format of List.To get the ScanResults from BroadcastReceiver we need to implement the onReceive () method

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

   @Override

   public void onReceive(Context context, Intent intent) {

     List<ScanResult> list= wifi.getScanResults();

       unregisterReceiver(this);

       for(ScanResult scanResult:list){

//SSID to recognise wifi networks, and we can get capabilities of the wifi // by using the class ScanResullt

           arrayList.add(scanResult.SSID);

          adapter.notifyDataSetChanged();

          }

   }

};

To start the scan and to get the wifi List we need to register the BroadcastReceiver

registerReceiver(broadcastReceiver,newIntentFilter(wifi.SCAN_RESULTS_AVAILABLE_ACTI

ON));

//To start the scan.

wifi.startScan();

Even if we have the permission to access location in AndroidManifest.xml to get the wifi list the app should ask the user for COARSE_LOCATION runtime permission. The onResume() method is used to ask for permission

@Override

public void onResume()

{

   super.onResume();

//To check the API version>= 23.

   if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)

   {

       if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)

       {

           requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 87);

       }

   }

}

Connect to Particular wifi

We need to choose the wifi network to connect. Which can be done by setOnItemClickListener()method. Using this method we can get the wifi SSID

  • wifilist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  •    @Override
  •    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  •        ssid = parent.getItemAtPosition(position).toString();
  • });

To connect to a particular network WifiConfiguration class is used which uses SSID and PreSharedKey as argument.

(PreSharedKey will be the user input and in this case denoted by “key” )

  • WifiConfiguration conf =conf = new WifiConfiguration();
  • conf.SSID = “\”” + ssid + “\””;
  • if (key == null) {
  • //If network is open
  •    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
  • } else {
  •    conf.preSharedKey = “\”” + key + “\””;
  • }

The established configuration is passed as argument to addNetwork()method of WifiManager class

  • int netID = wifi.addNetwork(conf);
  • //To disconnect the already connected network
  • wifi.disconnect();
  • //To connect to new established wifi Configuration
  • wifi.enableNetwork(netID, true);
  • wifi.reconnect();

6 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *