Ofek Agmon Ofek Agmon - 2 months ago 41
Android Question

Android Wifi Scan - BroadcastReceiver for SCAN_RESULTS_AVAILABLE_ACTION not getting called

Here is my code:

public class FloatWifiManager implements IWifiManager {

private WifiManager wifiManager;

private BroadcastReceiver wifiScanReceiver;

public FloatWifiManager(Context context) {
...
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

// Registering Wifi Receiver
wifiScanReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent intent) {
if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
// not getting called, only after running app and manually going to the wifi settings in android
}
}
};

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
context.registerReceiver(wifiScanReceiver, intentFilter);
wifiManager.startScan();
}


I registered the
BroadcastReceiver
exactly like I saw in all the examples, and did
startScan
.

What happens is, the wifi list is changing (for sure, I tested), but
onReceive
is not called if I just stay in the app.

What makes
onReceive
finally to be called - is to launch the app, leave it running, and going in the android phone to Settings -> Wifi settings. when going there, all of the sudden the List is updating and
onReceive
is called.

What's the problem here?


  1. Does
    wifiManager.startScan();
    runs the scan only once? or it is a function that keeps listening to incoming "Scan Results"?

  2. And obviously, why does the receiver doesn't get called?


Answer

Yes, startScan() requests only one single scan.

You can get rid of the if (intent.getAction().equals(..)) condition. Anything else seems to be ok.

You can see my scan example here (Scan for access points)

just to make it clear - my goal to have a receiver that will get called every time the Wifi networks list are changing, without having to click a "start scan" button.

AFAIK it is not possible to get notified whenever any of the wifi networks change. You can only request a scan with startScan - and of course you can call startScan repeatedly using a Thread or Handler.

The docs say that SCAN_RESULTS_AVAILABLE_ACTION is called when "an access point scan has completed, and results are available from the supplicant". How and when a scan is proceeded depends on the implemention of the supplicant. Elenkov writes, that "Android devices rarely include the original wpa_supplicant code; the included implementation is often modified for better compatibility with the underlying SoC".

Comments