Wi-Fi scanning without broadcast receiver?

十年热恋 提交于 2019-12-07 07:14:55

问题


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.


回答1:


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 call getScanResults() 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 to SCAN_RESULTS_AVAILABLE_ACTION.



来源:https://stackoverflow.com/questions/6305219/wi-fi-scanning-without-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!