What interval should I use between each WiFi scan on Android?

前端 未结 2 1160
渐次进展
渐次进展 2020-12-30 13:17

I need to perform Wifi scans at regular intervals. I am encountering a problem when the time interval is set to 1-2 seconds. It seems like I am not getting any ScanRes

相关标签:
2条回答
  • 2020-12-30 13:34

    From Android 8 and higher, the limit is 4 times in 2 minutes. So you could scan 4 times with 1 second of delay in between. But you would not get any further scan results for the next 126 seconds.

    So the fastest interval where every scan is successful would be every 30 seconds.

    0 讨论(0)
  • 2020-12-30 13:43

    EDIT after you posted your code:

    apdataList does not seem to be initialized in onCreate()

    add this to onCreate():

    apdataList = new List<APData>();
    

    Minimum scanning delay

    I think that there is no absolute minimum scanning delay. It depends too much on the hardware performances.

    My advice is that you add a 'As Fast As Possible' option to your preferences then use an asynchronous loop that relaunch a scan as soon as new results are found (see the code snippet below, it was updated to suit your needs). This way, it will only be limited by hardware performances.


    Also you can poll the ScanResults using WifiManager.getScanResults() The recommended way is to launch WifiManager.startScan() and set up a BroadcastReceiver for WifiManager.SCAN_RESULTS_AVAILABLE_ACTION to be notified as soon as the scan results are ready.

    Here's a sample code (borrowed from here and adapted to your needs):

    IntentFilter i = new IntentFilter(); 
    i.addAction (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); 
    registerReceiver(new BroadcastReceiver(){ 
          public void onReceive(Context c, Intent i){ 
          // Code to execute when SCAN_RESULTS_AVAILABLE_ACTION event occurs 
          WifiManager w = (WifiManager) c.getApplicationContext().getSystemService(Context.WIFI_SERVICE); //Use getApplicationContext to prevent memory leak
          myScanResultHandler(w.getScanResults()); // your method to handle Scan results
          if (ScanAsFastAsPossible) w.startScan(); // relaunch scan immediately
          else { /* Schedule the scan to be run later here */}
          } 
        }, i ); 
    
    
        // Launch  wifiscanner the first time here (it will call the broadcast receiver above)
        WifiManager wm = (WifiManager)getApplicationContext.getSystemService(Context.WIFI_SERVICE); 
        boolean a = wm.startScan(); 
    
    0 讨论(0)
提交回复
热议问题