Wi-Fi scan without a broadcast receiver?

I created a wifi scanner. It constantly scans available wi-fi networks. But my question is, why exactly transmit the receiver, if I can really start the scan (call startScan() with a timer every x seconds) and get the same results without creating a broadcast receiver?

This is the code of the broadcast receiver in onCreate() :

 i = new IntentFilter(); i.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); receiver = new BroadcastReceiver(){ public void onReceive(Context c, Intent i){ WifiManager w = (WifiManager) c.getSystemService(Context.WIFI_SERVICE); List<ScanResult> l = w.getScanResults(); for (ScanResult r : l) { // do smth with results } // log results } }; 

In the scan method, which is called after clicking the scan button, I:

 timer = new Timer(true); timer.schedule(new WifiTimerTask(), 0, scanningInterval); registerReceiver(receiver, i ); 

where is WifiTimerTask -

 publlic class WifiTimerTask extends TimerTask{ @Override public void run(){ wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); if (wifi.isWifiEnabled()) { wifi.startScan(); List<ScanResult> sc = wifi.getScanResults(); for (ScanResult r : l) { // do smth with results } // log results } } } 

And the fact is that scanning can be performed without registerReceiver(receiver,i) . However, only if scanningInterval below 2s, then receiver scanresults and startScan() not synchronized. By this, I mean startScan() results do not change until the receiver receives new results. Meanwhile, in logCat, I get ERROR/wpa_supplicant(5837): Ongoing Scan action... 2s seems to be the lowest scan interval. Please correct me if my assumptions are wrong.

+4
source share
1 answer

When you call startScan() , you do not know how long the actual scan will take (usually it can be 1 ms or 5 hours). Therefore, you cannot reliably call getScanResults() , as you do not know when the scan is complete.

To track the event when getScanResults() returns the results of an update scan, you need to subscribe to SCAN_RESULTS_AVAILABLE_ACTION .

+2
source

All Articles