An alternative for WifiManager's startScan() deprecated method on Android 11 and above?

1k views Asked by At

I figured out a couple of opened threads on the community referring to this issue, but there's no resolution on it. I see that Android documentation is referencing startScan() in the code snippet as an agreed approach initially, like here. All good, but we go further and we can observe this method which is deprecated for a long while, so they don't provide an official alternative for it yet. I understood the downsides and why they wanted to mark this as deprecated, but I consider that that they should not leave this situation "in the air", and this feature still needs be available in a way or another.

After some research I found this single API method which should do the trick for recent Android versions:

public void registerScanResultsCallback (Executor executor, 
            WifiManager.ScanResultsCallback callback)

Reference of the above snippet right here.

From an unofficial source I deduce that the above should replace startScan() call, so no need of calling it anymore, and it seems to be a workaround. However, I gave it a try, but the method does not trigger a scan implicitly and I'm not convinced that this should happen (from its name). In conclusion, this "workaround" it doesn't seem to work.

Does anyone has to deal with this problem and found a solution?



P.S: NEARBY_WIFI_DEVICES (for Android 13+), ACCESS_FINE_LOCATION and ACCESS_WIFI_STATE should be the needed permissions. If the scanning is invoked with startScan() or when opening Internet Settings screen (after fetching networks), the registrered callback is fired.

1

There are 1 answers

1
Patrick On

Yes, the startScan() method in the WifiManager class is indeed deprecated in Android 11 and above. The recommended alternative is to use the WifiManager.startScan() method in conjunction with the registerScanResultsCallback() method, which was introduced in Android 12.

Here's an example of how to use it:

Executor executor = ContextCompat.getMainExecutor(context);
ScanResultsCallback callback = new ScanResultsCallback() {
    @Override
    public void onScanResultsAvailable() {
        // Handle scan results here
    }
};
wifiManager.registerScanResultsCallback(executor, callback);
wifiManager.startScan();