javaandroidwifimanager

wifiManager.getScanResult() returns null value


I'm searching to do a scan of available wifi networks but the method getScanResults() returns null list.

I included all permissions needed :

android.permission.ACCESS_COARSE_LOCATION
android.permission.CHANGE_WIFI_STATE
android.permission.ACCESS_FINE_LOCATION
android.permission.ACCESS_WIFI_STATE

The main activity class is :

public class Home extends Activity {`

    Context context;
    WifiManager wifiManager = null;
    WiFiReceiver wifiReceiver = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);

        context = this;
        wifiManager = (WifiManager) 
        context.getSystemService(Context.WIFI_SERVICE);
        wifiReceiver = new WiFiReceiver(wifiManager);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        registerReceiver(wifiReceiver, intentFilter);

        wifiManager.startScan();
        List<ScanResult> results = wifiReceiver.results;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(wifiReceiver);
    }
}

The Broadcast Receiver is :

public class WiFiReceiver extends BroadcastReceiver {`

    public List<ScanResult> results;
    private WifiManager wifiManager;

    public WiFiReceiver(WifiManager wifiManager) {
        this.wifiManager = wifiManager;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        boolean success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false);
        if (success) {
            results = wifiManager.getScanResults();
            Log.e("wiFi Manager", "Done");

        } else {
            Log.e("wiFi Manager", "Scan failure");
        }
    }
}

Solution

  • The issue is that your are assuming that startScan() will produce a result immediately but it actually only does what is says, starting the scan. Your are accessing then results variable before onReceive in your WiFiReceiver has been triggered which is why it will always be null (your logging should confirm that).

    What you need to to is use a callback to get the results when they're ready like the code here does. Notice how the onReceive method calls scanSuccess() and the results are only accessed in scanSuccess() and not immediately after calling startScan(). Also notice how they are checking if starting the scan was actually successful by checking the Boolean startScan() returns