I have been struggling with automatically turning on Wi-Fi as soon as the device is within range of an access point without turning on the screen. It has been very frustrati
Had a second go around in the area. While the above solution did work for all our qualified devices, there were too many calls that might have been unnecessary. Plus we got new device for which the solution did not work. Here is a much better solution:
At every interval this code is called
NetworkInfo wifiInfo = _androidConnectivityMgr.GetNetworkInfo(ConnectivityType.Wifi);
if (!wifiInfo.IsConnectedOrConnecting)
{
// Need to make sure the CPU does not go to sleep before the following async calls are finished
_wifiScanWakeLock.Acquire();
// Do not wait for the OS to initiate a reconnect to a Wi-Fi router
_wifiManager.StartScan();
}
When the Wi-Fi scan is finished
private void OnWifiScanResultsReceived(Intent result)
{
NetworkInfo wifiInfo = _androidConnectivityMgr.GetNetworkInfo(ConnectivityType.Wifi);
if (!wifiInfo.IsConnectedOrConnecting)
{
Dictionary savedNetworks = new Dictionary();
foreach (WifiConfiguration config in _wifiManager.ConfiguredNetworks)
{
string escapedSsid = Regex.Replace(config.Ssid, "^\"|\"$", String.Empty);
savedNetworks[escapedSsid] = config.NetworkId;
}
foreach (ScanResult ap in _wifiManager.ScanResults)
{
int networkId;
if (savedNetworks.TryGetValue(ap.Ssid, out networkId))
{
savedNetworks.Remove(ap.Ssid);
_wifiManager.EnableNetwork(networkId, false);
}
}
}
_wifiScanWakeLock.Release();
}