Search code examples
androidandroid-wifiwifimanager

How to actively request for scans


How to actively request for scans?

The only way provided by the WifiManager API, as I understand it, is the startScan() method, which just starts a receiver to listen for the Wi-Fi service scans. The problem is the delay between scans, it takes too much time! If I do not move too much, no scans are received, and if I do, it takes too much time to notice.

Is there a way to dynamically request a scan?

This is the code I use:

    // ...
    wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    context.registerReceiver(this, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    wifi.startScan();
}

// ...

@Override
public void onReceive(Context context, Intent intent)
{
    List<ScanResult> results = this.wifi.getScanResults();
    // ...

Edit:

If it isn't clear...

The onReceive method receives scans sometimes, but it takes too long. I want to trigger a scan, not just wait for it comes. It can be done in a thread, repeatedly making it scan, as @Barns suggested.


Solution

  • The preferred coding solution would incorporate a Handler with a postDelayed instead of Thread.sleep. It is important to remove any Callbacks!

    Try something like this:

    private boolean continueLoop = true;
    private Handler myHandler = new Handler();
    
    private void startAutoDownloadManager() {
        try{
            Log.d(TAG, "AutoDownloadManager - Started");
            // here the delay (in this example it is effectively the interval) is 1 second
            myHandler.postDelayed(mAutoDownloadManager, 1000);
        }
        catch(Exception ex){
            Log.e(TAG, ex.getMessage());
        }
    }
    
    private Runnable mAutoDownloadManager = new Runnable() {
        public void run() {
            if(continueLoop){
                // preform the scan
                this.wifi.startScan();
    
                //re-trigger the call to start the scan
                startAutoDownloadManager();
            {
        }
    };
    
    // Make certain that you remove the callback when you leave the activity -- maybe in onPause()
    private void stopAutoDownloadManager(){
        try{
            myHandler.removeCallbacks(mAutoDownloadManager);
        }
        catch(Exception ex){
            Log.e(TAG, ex.getMessage());
        }
    }