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

You need to create a BroadcastReceiver to listen for Wifi scan results:

private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context c, Intent intent) {
        if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
            List<ScanResult> mScanResults = mWifiManager.getScanResults();
            // add your logic here
        }
    }
}

In onCreate() you would assign mWifiManager and initiate a scan:

mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
registerReceiver(mWifiScanReceiver,
        new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mWifiManager.startScan();

getScanResults() will return data only if you have appropriate permissions. For this, add one of the following two lines to your AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Also note that in API 23+, permissions must be requested at runtime. (For a lab environment, you can also grant permissions manually in Settings instead—less coding required, but not recommended for an end-user app.)

Note that the code which handles your scan results would run every time a new scan result is available, updating the result.

Leave a Comment