Forum Xamarin.Android
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Connect to a specified WIFI(WAP) not working

I trying to Connect the Wifi(WAP) ,but its not connecting.Please any one help on this .Here is my code.

    public Task<string> ConnectToWifi(string wifiSSID, string wifiPWD)
    {
        DateTime requestStartTime = DateTime.Now;
        TaskCompletionSource<string> taskCompletionSource = new TaskCompletionSource<string>();

        //Configure the SSID And PWD into WifiConfiguration
        //Please note the quotes. String should contain ssid in quotes
        var formattedSsid = "\"" + wifiSSID + "\""; 
        var formattedPassword = "\"" + wifiPWD + "\""; 
        WifiConfiguration wifiConfig = new WifiConfiguration
        {
            Ssid = formattedSsid,
            PreSharedKey = formattedPassword,
            StatusField = WifiStatus.Enabled,
            Priority = 40
        };
        wifiConfig.AllowedProtocols.Set((int)ProtocolType.Rsn);
        wifiConfig.AllowedProtocols.Set((int)ProtocolType.Wpa);
        wifiConfig.AllowedKeyManagement.Set((int)KeyManagementType.WpaPsk);
        wifiConfig.AllowedPairwiseCiphers.Set((int)PairwiseCipherType.Ccmp);
        wifiConfig.AllowedPairwiseCiphers.Set((int)PairwiseCipherType.Tkip);
        wifiConfig.AllowedGroupCiphers.Set((int)GroupCipherType.Wep40);
        wifiConfig.AllowedGroupCiphers.Set((int)GroupCipherType.Wep104);
        wifiConfig.AllowedGroupCiphers.Set((int)GroupCipherType.Ccmp);
        wifiConfig.AllowedGroupCiphers.Set((int)GroupCipherType.Tkip);
        wifiConfig.AllowedAuthAlgorithms.Set((int)AuthAlgorithmType.Open);

        WifiManager wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);

        //Enable the Wi-fi
        wifiManager.SetWifiEnabled(true);

        //Add the Wifidetails into WifiConfiguration
        var addNetwork = wifiManager.AddNetwork(wifiConfig);
        var network = wifiManager.ConfiguredNetworks.FirstOrDefault(n => n.Ssid == formattedSsid);

        if (network == null)
        {
            Device.StartTimer(TimeSpan.FromSeconds(1), () =>
            {
                taskCompletionSource.SetResult("internal error");
                return false;
            });
        }
        else
        {

            // Make sure network hasn't changed
            wifiManager.UpdateNetwork(wifiConfig);

            //Disconnect the Wi-fi
            wifiManager.Disconnect();

            //Enable the Wi-fi
            wifiManager.EnableNetwork(network.NetworkId, true);

            //ReConnect the Wi-fi
            wifiManager.Reconnect();

            //Get the reponse from the WifiReceiver BroadcastReceiver
            MainActivity.isWifiOnReceived = false;
            MainActivity.mWifiConnectionReceiver.RegisterTaskCompletionSource(taskCompletionSource, formattedSsid);

            //Wifi connection request not responsed means after 20seconds  request has cancelled
            requestStartTime = DateTime.Now;
            Device.StartTimer(TimeSpan.FromSeconds(20), () =>
            {
                MainActivity.UserDisconnected = "";
                var dateDiff = DateTime.Now - requestStartTime;
                if (dateDiff.Seconds == 20 && !MainActivity.isWifiOnReceived)
                {
                    try
                    {
                        wifiManager.RemoveNetwork(network.NetworkId);
                        if (taskCompletionSource != null)
                        {
                            taskCompletionSource?.SetResult("internal error");
                        }
                    }
                    catch
                    {
                        MainActivity.isWifiOnReceived = false;
                    }
                }
                return MainActivity.isWifiOnReceived;
            });
        }
        return taskCompletionSource.Task;
    }

Thanks,
Ramya.

Best Answers

  • RamyaSowmianRamyaSowmian USMember
    Accepted Answer

    I have found the issue and fixed it. It's working fine.

    wifiConfig.HiddenSSID = true;

Answers

  • RamyaSowmianRamyaSowmian USMember

    Hi Jarvan,

    Thank you for your response.

    The open hotspot wifi connection is working fine.

    I am using one of the device hidden secured wifi with no internet but it's not connecting. iOS is working fine android only the problem.

    Thanks,
    Ramya.

  • RamyaSowmianRamyaSowmian USMember
    Accepted Answer

    I have found the issue and fixed it. It's working fine.

    wifiConfig.HiddenSSID = true;

  • CaptainXamtasticCaptainXamtastic GBUniversity ✭✭✭
    edited January 9

    Can anyone explain the following conundrum?

    Using @Jarvan 's code above, the following modification to his code works in both his demo app, and mine:

            private void connect_to()
            {
                const string ssid = "\"PLUSNET-2TK3\"";
                const string password = "\"72562da64c\"";
    
                string s = "PLUSNET-2TK3";
                string p = "72562da64c";
    
                string _ssid = $"\"{s}\"";
                string _password = $"\"{p}\"";
    
    
                var wifiConfig = new WifiConfiguration
                {
                    Ssid = _ssid,
                    PreSharedKey = _password
                };
    
                var wifiManager = GetSystemService(WifiService).JavaCast<WifiManager>();
                var addNetwork = wifiManager.AddNetwork(wifiConfig);
            }
    

    I made the modifications because I want to do it dynamically, instead of using the const keyword.

    However the following works in his demo app, but not in mine:

            private void connect_to(string s, string p)
            {
                string _ssid = $"\"{s}\"";
                string _password = $"\"{p}\"";
    
    
                var wifiConfig = new WifiConfiguration
                {
                    Ssid = _ssid,
                    PreSharedKey = _password
                };
    
                var wifiManager = GetSystemService(WifiService).JavaCast<WifiManager>();
                var addNetwork = wifiManager.AddNetwork(wifiConfig);
            }
    

    although I call

            public async Task AddWifiAPToSavedConfigurations(string ssid, string password)
            { 
                string s = "PLUSNET-2TK3";
                string p = "72562da64c";
    
                connect_to(s, p);
            }
    

    from another method, and that works, the following does not work:

            public async Task AddWifiAPToSavedConfigurations(string ssid, string password)
            { 
                string s = "PLUSNET-2TK3";
                string p = "72562da64c";
    
                connect_to(ssid, password);
            }
    

    Here, the ssid and password variables were received by W-Fi P2P from another app, hence were never hard-coded anywhere.

    It's as though the system wants hard-coded values, any pointers?

    I'm trying to achieve this dynamically, instead of using hard-coded values!

    Kind regards,

    Anthony

Sign In or Register to comment.