Trouble with connecting to wifi in code in Xamarin

Viewed 62

I've been trying to connect to a specific wifi through code, but with no succcess. This is what i've come up with:

public void ConnectToWifi(string ssid, string password)
        {
            WifiManager wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);

            if (!wifiManager.IsWifiEnabled)
            {
                wifiManager.SetWifiEnabled(true);
            }

            string formattedSsid = $"\"{ssid}\"";
            string formattedPassword = $"\"{password}\"";

            WifiConfiguration wifiConfig = new WifiConfiguration
            {
                Ssid = formattedSsid,
                PreSharedKey = formattedPassword
            };

            var addNetwork = wifiManager.AddNetwork(wifiConfig);

            WifiConfiguration network = wifiManager.ConfiguredNetworks.FirstOrDefault(n => n.Ssid == ssid);

            if (network == null)
            {
                Console.WriteLine($"Cannot connect to network: {ssid}");
                return;
            }

            wifiManager.Disconnect();
            bool enableNetwork = wifiManager.EnableNetwork(network.NetworkId, true);
        }

I've added permissions. When testing it does turn the wifi on atleast, so i know it works until that point. What seems not to be working is the AddNetwork part.

I appreciate any help i can get!

1 Answers

You are missing one key method - reconnect(). You can read more about it in the WifiManager's docs here

The important part of the documentation is:

Reconnect to the currently active access point, if we are currently disconnected.

So, what you need to do it after you have disconnected and enabled your new network, call in the end this and you will be good to go:

wifiManager.Disconnect();
wifiManager.EnableNetwork(network.NetworkId, true);
wifiManager.Reconnect(); // This is the missing method

NB: Keep in mind that most of the WifiManager's code that you are using is being obsolete starting Android 10. So, if you want to target Android 10, then you will need to write an additional code for the connectivity for devices with Android 10+.

Related