How to get available wifi networks and display them in a list in android

AndroidApps/ApplicationsMobile Development

This example demonstrate about How to get available wifi networks and display them in a list in android

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.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"
   android:layout_margin = "16dp"
   android:orientation = "vertical"
   tools:context = ".MainActivity">
   <ListView
      android:id = "@+id/wifiList"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent"
      android:layout_above = "@+id/scanBtn" />
   <Button
      android:id = "@+id/scanBtn"
      android:layout_width = "match_parent"
      android:layout_height = "50dp"
      android:layout_alignParentBottom = "true"
      android:layout_gravity = "bottom"
      android:layout_margin = "15dp"
      android:text = "Scan WiFi" />
</RelativeLayout>

Step 3 − Add the following code to src/MainActivity.java

package com.example.myapplication;

import android.Manifest;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
   private ListView wifiList;
   private WifiManager wifiManager;
   private final int MY_PERMISSIONS_ACCESS_COARSE_LOCATION = 1;
   WifiReceiver receiverWifi;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      wifiList = findViewById(R.id.wifiList);
      Button buttonScan = findViewById(R.id.scanBtn);
      wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
      if (!wifiManager.isWifiEnabled()) {
         Toast.makeText(getApplicationContext(), "Turning WiFi ON...", Toast.LENGTH_LONG).show();
         wifiManager.setWifiEnabled(true);
      }
      buttonScan.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
               ! = PackageManager.PERMISSION_GRANTED) {
               ActivityCompat.requestPermissions(
               MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_ACCESS_COARSE_LOCATION);
            } else {
               wifiManager.startScan();
            }
         }
      });
   }
   @Override
   protected void onPostResume() {
      super.onPostResume();
      receiverWifi = new WifiReceiver(wifiManager, wifiList);
      IntentFilter intentFilter = new IntentFilter();
      intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
      registerReceiver(receiverWifi, intentFilter);
      getWifi();
   }
   private void getWifi() {
      if (Build.VERSION.SDK_INT > = Build.VERSION_CODES.M) {
         Toast.makeText(MainActivity.this, "version> = marshmallow", Toast.LENGTH_SHORT).show();
         if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
            ! = PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(MainActivity.this, "location turned off", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
               MY_PERMISSIONS_ACCESS_COARSE_LOCATION);
         } else {
            Toast.makeText(MainActivity.this, "location turned on", Toast.LENGTH_SHORT).show();
            wifiManager.startScan();
         }
      } else {
         Toast.makeText(MainActivity.this, "scanning", Toast.LENGTH_SHORT).show();
         wifiManager.startScan();
      }
   }
   @Override
   protected void onPause() {
      super.onPause();
      unregisterReceiver(receiverWifi);
   }
   @Override
   public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
      super.onRequestPermissionsResult(requestCode, permissions, grantResults);
      switch (requestCode) {
         case MY_PERMISSIONS_ACCESS_COARSE_LOCATION:
         if (grantResults.length > 0 && grantResults[0] = = PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(MainActivity.this, "permission granted", Toast.LENGTH_SHORT).show();
            wifiManager.startScan();
         } else {
            Toast.makeText(MainActivity.this, "permission not granted", Toast.LENGTH_SHORT).show();
            return;
         }
         break;
      }
   }
}

Step 4 − Add the following code to src/WifiReceiver

package com.example.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

class WifiReceiver extends BroadcastReceiver {
   WifiManager wifiManager;
   StringBuilder sb;
   ListView wifiDeviceList;
   public WifiReceiver(WifiManager wifiManager, ListView wifiDeviceList) {
      this.wifiManager = wifiManager;
      this.wifiDeviceList = wifiDeviceList;
   }
   public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
         sb = new StringBuilder();
         List<ScanResult> wifiList = wifiManager.getScanResults();
         ArrayList<String> deviceList = new ArrayList<>();
         for (ScanResult scanResult : wifiList) {
            sb.append("\n").append(scanResult.SSID).append(" - ").append(scanResult.capabilities);
            deviceList.add(scanResult.SSID + " - " + scanResult.capabilities);
         }
         Toast.makeText(context, sb, Toast.LENGTH_SHORT).show();
         ArrayAdapter arrayAdapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, deviceList.toArray());
         wifiDeviceList.setAdapter(arrayAdapter);
      }
   }
}

Step 5 − Add the following code to androidManifest.xml

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
   package = "com.example.myapplication">
   <uses-permission android:name = "android.permission.ACCESS_COARSE_LOCATION" />
   <uses-permission android:name = "android.permission.ACCESS_WIFI_STATE" />
   <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 = "com.example.myapplication.MainActivity">
         <intent-filter>
            <action android:name = "android.intent.action.MAIN" />
            <category android:name = "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –

Click here to download the project code

raja
Published on 15-Apr-2019 16:27:58
Advertisements