I have created wi-fi scanner. It continually scans for available wi-fi networks. But my question is why would exactly broadcast receiver is needed if i can actually run scanning (invoke startScan()
with timer every x seconds) and receive the same results without creating broadcast receiver?
This is broadcast receiver code in onCreate()
method:
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 scanning method, which is invoked after scan button is pressed I have:
timer = new Timer(true);
timer.schedule(new WifiTimerTask(), 0, scanningInterval);
registerReceiver(receiver, i );
where WifiTimerTask
is
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 point is that scanning can be performed without registerReceiver(receiver,i)
. However only if scanningInterval
is lower than 2s, then receiver
scanresults and startScan()
are not synchronized. By that I mean startScan()
results do not change until receiver
will get new results. Meanwhile in logCat I get ERROR/wpa_supplicant(5837): Ongoing Scan action...
. Seems like 2s is the lowest scanning interval though. Please correct me if my assumptions are wrong.
When you call
startScan()
you don't know how long the actual scan will take (generally speaking it can be 1 ms or 5 hours). So you cannot reliably callgetScanResults()
as you don't know when the scan is completed.To track the event when when
getScanResults()
will return update scan results you need to subscribe toSCAN_RESULTS_AVAILABLE_ACTION
.