Android : Reconnect to Wi-Fi after entering coverage area while screen turned off

后端 未结 3 802
迷失自我
迷失自我 2020-12-05 22:34

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

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 22:46

    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();
    }
    
    • _wifiScanWakeLock is just a partial, non-reference counted WakeLock, Dispose in OnDestroy

    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();
    }
    
    • BSSID for the WifiConfiguration is always null and cannot be used that to uniquely compare to the BSSID of the ScanResult
    • This is the core code, obviously you would have to worry about case of two identical SSIDs and other optimizations

提交回复
热议问题