質問

I want to get the result of the WiFi scan only when I call startScan(), but what I get is the that the results keep changing even though I called startScan() only once . My point is I want to update the scan results only when calling startScan() .

I read about WIFI_MODE_SCAN_ONLY, it says

In this Wi-Fi lock mode, Wi-Fi will be kept active, but the only operation that will be supported is initiation of scans, and the subsequent reporting of scan results. No attempts will be made to automatically connect to remembered access points, nor will periodic scans be automatically performed looking for remembered access points. Scans must be explicitly requested by an application in this mode.

I don't want to have periodic scans unless I call startScan() , but I have no idea were to set that flag I have tried to pass this way

      receiverWifi = new WifiReceiver();
      registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

Any help is really appreciated , I have been working on solving this for so long.

役に立ちましたか?

解決

I suppose the OP has found some solutions or workaround. If not and for anyone else (like me) looking for an easy solution, here's what I did:

  1. Declare a global variable: Boolean singleScanMode = false;

  2. Create a method and call it whenever I need to scan for available APs:

public void scanAps() {

WifiManager tempWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
// set singleScanMode = true so you can collect scan data
singleScanMode = true;
// add intent filters to enable auto scan 
IntentFilter i = new IntentFilter(); 
i.addAction(tempWifiManager.SCAN_RESULTS_AVAILABLE_ACTION); 

registerReceiver(new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
        //ignore scan results unless singleScanMode is set to 
        if (singleScanMode) { 
            List<ScanResult> results = tempWifiManager.getScanResults(); 
            Iterator<ScanResult> iterator = results.iterator(); 
            Toast.makeText(context, "Total APs found: "  
            + results.size(), Toast.LENGTH_SHORT).show();

            while (iterator.hasNext()) { 
                ScanResult next = iterator.next();  
                final String bssid = next.BSSID; // MAC address 
                final String ssid = next.SSID; // AP name 
                final int rssi = next.level; // Received Signal Strength Indicator 
                // do anything else you want 
            }  // end while
            //set it back to false
            singleScanMode = false; 
        }  //end if
    }, i); 
    tempWifiManager.startScan();

}

Note that, Android will report to you Activity whenever wifi is scanned, as long as the Activity is running. But this way you just ignore the scan results. And if anyone else has a better idea please share. Hope it helps!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top