示例#1
0
        /*コンストラクタ*/
        //public void Sample_WifiConnection(Context context)
        //{
        //    wifi = (WifiManager)context.GetSystemService(Context.WifiService);
        //}

        //IPアドレスの取得
        string getIpAddress()
        {
            WifiConfiguration wifiConfig = new WifiConfiguration();

            wifi = (WifiManager)Application.Context.GetSystemService(Context.WifiService);
            WifiInfo wifiinfo = (WifiInfo)Application.Context.GetSystemService(Context.WifiService);

            //int netId = WifiManager.addNetwork(wifiConfig);
            wifi.Disconnect();
            //wifi.EnableNetwork(netId, true);
            wifi.Reconnect();
            int iPAddress = wifiinfo.IpAddress;
            //return iPAddress;

            int ipAddress_int = wifi.ConnectionInfo.IpAddress;

            if (ipAddress_int == 0)
            {
                ipAddress = null;
            }
            else
            {
                ipAddress = (ipAddress_int & 0xFF) + "." + (ipAddress_int >> 8 & 0xFF) + "." + (ipAddress_int >> 16 & 0xFF) + "." + (ipAddress_int >> 24 & 0xFF);
            }
            return(ipAddress);
        }
示例#2
0
        private void StartAPBtn_Click(object sender, System.EventArgs e)
        {
            WifiConfiguration config = new WifiConfiguration();

            config.HiddenSSID = HideSSID.Checked;
            config.Ssid       = SSID.Text;
            config.AllowedKeyManagement.Set((int)KeyManagementType.WpaPsk);
            config.PreSharedKey = Password.Text;

            bool result = false;

            if (wifiApManager.IsWifiApEnabled())
            {
                result = wifiApManager.SetWifiApConfiguration(config);
            }
            else
            {
                result = wifiApManager.SetWifiApEnabled(config, true);
            }

            if (result)
            {
                Toast.MakeText(this, "AP Turned On", ToastLength.Short).Show();
            }
            else
            {
                Toast.MakeText(this, "Unable to turn AP on", ToastLength.Short).Show();
            }
        }
示例#3
0
        private void WpaOkClicked(object sender, DialogClickEventArgs e)
        {
            var dialog   = (AlertDialog)sender;
            var password = (EditText)dialog.FindViewById(Resource.Id.password);

            var conf = new WifiConfiguration();

            conf.Ssid         = "\"" + mSelectedSsid + "\"";
            conf.PreSharedKey = "\"" + password.Text + "\"";

            var wifiManager = GetSystemService(WifiService).JavaCast <WifiManager>();

            int id = wifiManager.AddNetwork(conf);

            IList <WifiConfiguration> myWifi = wifiManager.ConfiguredNetworks;

            WifiConfiguration wc = myWifi.First(x => x.Ssid.Contains(mSelectedSsid));

            wifiManager.Disconnect();
            wifiManager.EnableNetwork(wc.NetworkId, true);
            wifiManager.Reconnect();

            if (wifiManager.IsWifiEnabled)
            {
                StartActivity(typeof(DataTransferActivity));
            }
        }
示例#4
0
        //public void CreateAutoHotspot()
        //{
        //    try
        //    {
        //        //if (!_wifiManager.IsWifiEnabled)
        //        //{
        //        //    OnError?.Invoke(new Exception("Wireless network adapter is disabled"));
        //        //    return;
        //        //}

        //        // if WiFi is on, turn it off
        //        if (IsHotspotEnabled)
        //        {
        //            _wifiManager.SetWifiEnabled(false);
        //        }
        //        Device.BeginInvokeOnMainThread(() => {

        //            //_wifimanager.AddOrUpdatePasspointConfiguration(p);

        //            //var callback = new WifiManager.LocalOnlyHotspotCallback();

        //            _wifiManager.StartLocalOnlyHotspot(null,
        //            new Handler((m) =>
        //            {
        //                var d = m;
        //            }));
        //        });
        //        //Method setWifiApEnabledMethod = _wifimanager.Class.GetMethod("setWifiApEnabled", wificonfiguration.Class, Java.Lang.Boolean.Type);
        //        //setWifiApEnabledMethod.Invoke(_wifimanager, wificonfiguration, !IsHotspotEnabled);
        //        OnLog?.Invoke("LocalOnlyHostSpot has been requested");
        //    }
        //    catch (Exception ex)
        //    {
        //        OnError?.Invoke(new Exception("HotspotCreator can not create a hotspot network", ex));
        //    }
        //}

        public void CreateHotspot(string ssid, string preSharedPassword)
        {
            WifiConfiguration wificonfiguration = GetWifiApConfiguration();

            //wificonfiguration = new WifiConfiguration();
            wificonfiguration.HiddenSSID   = false;
            wificonfiguration.Ssid         = ssid;
            wificonfiguration.Bssid        = ssid;
            wificonfiguration.PreSharedKey = preSharedPassword;

            SetWifiApConfiguration(wificonfiguration);
            //wificonfiguration.
            try
            {
                // if WiFi is on, turn it off
                if (IsHotspotEnabled)
                {
                    _wifiManager.SetWifiEnabled(false);
                }
                //var setWifiApEnabledMethod = _wifimanager.Class.GetMethod("setWifiApEnabled", wificonfiguration.Class, Java.Lang.Boolean.Type);
                var setWifiApEnabledMethod = _wifiManager.Class.GetMethods().FirstOrDefault(m => m.Name == "setWifiApEnabled");
                setWifiApEnabledMethod.Invoke(_wifiManager, wificonfiguration, true);
                OnLog?.Invoke("HostSpot has been created");
            }
            catch (Exception ex)
            {
                OnError?.Invoke(new Exception("HotspotCreator can not create a hotspot network", ex));
            }
        }
示例#5
0
        private void OnConnectButtonClicked(object sender, EventArgs e)
        {
            device = (Models.Device)BindingContext;
            var wifiManager = (WifiManager)Android.App.Application.Context
                              .GetSystemService(Context.WifiService);
            string ssid              = device.Ssid;
            string password          = device.Password;
            var    formattedSsid     = string.Format("\"{0}\"", ssid);
            var    formattedPassword = string.Format("\"{0}\"", password);

            var wifiConfig = new WifiConfiguration
            {
                Ssid         = formattedSsid,
                PreSharedKey = formattedPassword
            };
            var addNetwork = wifiManager.AddNetwork(wifiConfig);

            var network = wifiManager.ConfiguredNetworks
                          .First(n => n.Ssid == formattedSsid);

            if (network == null)
            {
                label3.Text = "Errore di connessione,riprovare";
            }
            else
            {
                wifiManager.Disconnect();
                var enableNetwork = wifiManager.EnableNetwork(network.NetworkId, true);
                wifiManager.Reconnect();
                label3.Text = "Connesso";
            }
        }
        private async Task HandleDesiredPropertyChangeAsync(JToken desiredValue)
        {
            var    desiredConfig    = WifiConfiguration.Parse(desiredValue.ToString(), ConfigurationType.Desired);
            string connectionString = _connectionString;

            await ProcessDesiredWifiConfigurationAsync(connectionString, desiredConfig);
        }
示例#7
0
文件: Core.cs 项目: rhinohq/PULSE
                public static void ConnectToNework(string SSID, string Key)
                {
                    var WifiConfig = new WifiConfiguration();

                    WifiConfig.Ssid         = string.Format("\"{0}\"", SSID);
                    WifiConfig.PreSharedKey = string.Format("\"{0}\"", Key);

                    ToggleWiFi(true);

                    int NetID;
                    var Network = WifiMan.ConfiguredNetworks.FirstOrDefault(cn => cn.Ssid == SSID);

                    if (Network != null)
                    {
                        NetID = Network.NetworkId;
                    }
                    else
                    {
                        NetID = WifiMan.AddNetwork(WifiConfig);

                        WifiMan.SaveConfiguration();
                    }

                    WifiMan.UpdateNetwork(WifiConfig);

                    var CurrCon = WifiMan.ConnectionInfo;

                    if (CurrCon != null && CurrCon.NetworkId != NetID)
                    {
                        WifiMan.Disconnect();
                        WifiMan.EnableNetwork(NetID, true);
                        WifiMan.Reconnect();
                    }
                }
示例#8
0
        public String connectToWifi(String ssid, String wifiPassword)
        {
            string            result;
            WifiConfiguration wifiConfiguration = new WifiConfiguration();

            wifiConfiguration.Ssid         = string.Format("\"{0}\"", ssid);
            wifiConfiguration.PreSharedKey = string.Format("\"{0}\"", wifiPassword);
            wifiManager.RemoveNetwork(wifiManager.ConnectionInfo.NetworkId);
            this.removeConfigById(wifiManager.ConnectionInfo.NetworkId);
            this.removeConfig(string.Format("\"{0}\"", ssid));
            this.removeConfig(ssid);

            //var wifiManager = (WifiManager)Android.App.Application.Context
            //        .GetSystemService(Context.WifiService);
            string old_ssid = string.Format("\"{0}\"", wifiManager.ConnectionInfo.SSID);

            old = wifiManager.ConfiguredNetworks.FirstOrDefault(n => n.Ssid == old_ssid);

            int netId = wifiManager.AddNetwork(wifiConfiguration);

            wifiManager.Disconnect();
            wifiManager.EnableNetwork(netId, true);
            wifiManager.Reconnect();

            result = wifiManager.ConnectionInfo.SSID;

            return(result);
        }
示例#9
0
        public async Task Connect(
            string ssid,
            string password = null,
            bool wep        = false,
            CancellationToken cancellationToken = default)
        {
            await Task.Run(() =>
            {
                var configuration = new WifiConfiguration {
                    Ssid = $"\"{ssid}\""
                };

                if (password == null)
                {
                    configuration.AllowedKeyManagement.Set((int)KeyManagementType.None);
                }
                else if (!wep)
                {
                    configuration.PreSharedKey = $"\"{password}\"";
                }
                else
                {
                    throw new NotImplementedException("Not going to support WEP right now.");
                }

                _wifiManager.AddNetwork(configuration);
                Reconnect(ssid);
            }, cancellationToken);
        }
示例#10
0
        /// <summary>
        /// Handles OnClick event for OK-button of password dialog.
        /// Tries to connect to the network and start ControllerActivity.
        /// </summary>
        private void WpaOkClicked(object sender, DialogClickEventArgs e)
        {
            var dialog = (AlertDialog)sender;

            // Get entered password
            var password = (EditText)dialog.FindViewById(Resource.Id.etDialogPassword);

            var conf = new WifiConfiguration();

            conf.Ssid         = "\"" + mSelectedSsid + "\"";
            conf.PreSharedKey = "\"" + password.Text + "\"";

            var wifiManager = GetSystemService(WifiService).JavaCast <WifiManager>();
            // Connect network
            int id = wifiManager.AddNetwork(conf);

            if (id != -1)
            {
                wifiManager.Disconnect();
                wifiManager.EnableNetwork(id, true);
                wifiManager.Reconnect();
                mLastConnectedPeer = mSelectedSsid;
                Intent intent = new Intent(BaseContext, typeof(ControllerActivity));
                // intent.PutExtra("isConnected", mIsConnected);
                intent.PutExtra("mac", mSelectedBssid);
                StartActivity(intent);
                //mIsConnected = true;
            }
            else
            {
                Toast.MakeText(this, "Could not connect to peer", ToastLength.Short).Show();
            }
        }
示例#11
0
        public bool Connect(string ssid, string password)
        {
            bool ret = false;

            try
            {
                var wifiManager       = (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);
                var formattedSsid     = $"\"{ssid}\"";
                var formattedPassword = $"\"{password}\"";
                var wifiConfig        = new WifiConfiguration
                {
                    Ssid         = formattedSsid,
                    PreSharedKey = formattedPassword
                };
                var network = wifiManager.ConfiguredNetworks.FirstOrDefault(n => n.Ssid == formattedSsid);
                if (network == null)
                {
                    var addNetwork = wifiManager.AddNetwork(wifiConfig);
                }
                wifiManager.Disconnect();
                var enableNetwork = wifiManager.EnableNetwork(network.NetworkId, true);
                ret = true;
            }
            catch (Exception ex) { }
            return(ret);
        }
示例#12
0
        /// <summary>
        /// 设置WiFi热点状态
        /// 如果没有设置那么按默认走
        /// </summary>
        public static bool SetWifiApEnabled(Context context, bool enabled, WifiapViewModel model)
        {
            var wifiManager = (WifiManager)context.GetSystemService(Context.WifiService);
            WifiConfiguration myConfig;

            if (model != null)
            {
                myConfig = new WifiConfiguration
                {
                    Ssid         = model.Ssid,
                    PreSharedKey = model.PreSharedKey
                };
                myConfig.AllowedAuthAlgorithms.Set((int)AuthAlgorithmType.Open);
                myConfig.AllowedKeyManagement.Set((int)GroupCipherType.Wep40);
            }
            else
            {
                var getWifiConfig = wifiManager.Class.GetMethod("getWifiApConfiguration", null);
                myConfig = (WifiConfiguration)getWifiConfig.Invoke(wifiManager, null);
                var setWifiConfig = wifiManager.Class.GetMethod("setWifiApConfiguration", myConfig.Class);
                setWifiConfig.Invoke(wifiManager, myConfig);
            }
            var enableWifi = wifiManager.Class.GetMethod("setWifiApEnabled", myConfig.Class, Boolean.Type);

            return((bool)enableWifi.Invoke(wifiManager, myConfig, enabled));
        }
 private void finallyConnect(string networkPass, string networkSSID)
 {
     try
     {
         using (Android.Net.Wifi.WifiManager wifi = (Android.Net.Wifi.WifiManager)ApplicationContext.GetSystemService(Context.WifiService))
         {
             if (wifi != null && wifi.IsWifiEnabled)
             {
                 using (WifiConfiguration wifiConfig = new WifiConfiguration())
                 {
                     wifiConfig.Ssid         = "\"" + networkSSID + "\""; //string.Format("\"%s\"", networkSSID);
                     wifiConfig.PreSharedKey = "\"" + networkPass + "\""; // string.Format("\"%s\"", networkPass);
                     int netId = wifi.AddNetwork(wifiConfig);
                     wifi.Disconnect();
                     wifi.EnableNetwork(netId, true);
                     wifi.Reconnect();
                     using (WifiConfiguration conf = new WifiConfiguration())
                     {
                         conf.Ssid         = "\"" + networkSSID + "\"";
                         conf.PreSharedKey = "\"" + networkPass + "\"";
                         wifi.AddNetwork(conf);
                     }
                 }
             }
         }
     }
     catch
     {
     }
 }
示例#14
0
        public void ConnectToWifi(string ssid, string password)
        {
            var wifiManager = (WifiManager)Android.App.Application.Context
                              .GetSystemService(Context.WifiService);

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

            wifiManager.SetWifiEnabled(true);

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

            var addNetwork = wifiManager.AddNetwork(wifiConfig);

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

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

            wifiManager.Disconnect();
            var enableNetwork = wifiManager.EnableNetwork(addNetwork, true);
        }
示例#15
0
        private void WepOkClicked(object sender, DialogClickEventArgs e)
        {
            var dialog   = (AlertDialog)sender;
            var password = (EditText)dialog.FindViewById(Resource.Id.password);

            var conf = new WifiConfiguration();

            conf.Ssid          = "\"" + mSelectedSsid + "\"";
            conf.WepKeys[0]    = "\"" + password + "\"";
            conf.WepTxKeyIndex = 0;
            conf.AllowedKeyManagement.Set((int)KeyManagementType.None);
            conf.AllowedPairwiseCiphers.Set((int)GroupCipherType.Wep40);

            var wifiManager = GetSystemService(WifiService).JavaCast <WifiManager>();

            wifiManager.AddNetwork(conf);
            WifiP2pDevice wifi = new WifiP2pDevice();

            foreach (var network in wifiManager.ConfiguredNetworks.Where(n => n.Ssid.Contains(mSelectedSsid)))
            {
                wifiManager.Disconnect();
                wifiManager.EnableNetwork(network.NetworkId, true);
                wifiManager.Reconnect();
            }
        }
示例#16
0
        /// <summary>
        /// Get the WiFi network details in a simple json format
        /// </summary>
        /// <param name="context">An Android context, eg. the main activity</param>
        /// <returns>A string containing the WiFi network detail in a JSON format</returns>
        public static string WifiHandshake(Context context)
        {
            WifiManager         wifiManager         = (WifiManager)context.GetSystemService(Context.WifiService);
            ConnectivityManager connectivityManager = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
            NetworkInfo         networkInfo         = connectivityManager.ActiveNetworkInfo;
            bool isRegularWifi = networkInfo.Type == ConnectivityType.Wifi;

            if (isRegularWifi)
            {
                int       ip       = wifiManager.ConnectionInfo.IpAddress;
                IPAddress address  = new IPAddress(BitConverter.GetBytes(ip));
                String    ipString = address.ToString();
                String    SSID     = wifiManager.ConnectionInfo.SSID;
                return("{\"wifi\": true, \"ssid\": " + SSID + ",\"ip\": \"" + ipString + "\"}");
            }
            else
            {
                // might be WiFi AP (hotspot). Let's check with this awful non-public API that might be removed in a later version
                Method isWifiApEnabled = wifiManager.Class.GetMethod("isWifiApEnabled");
                if ((Boolean)isWifiApEnabled.Invoke(wifiManager))
                {
                    // Yep. We're the AP, send over the SSID
                    Method            getWifiApConfiguration = wifiManager.Class.GetMethod("getWifiApConfiguration");
                    WifiConfiguration config = (WifiConfiguration)getWifiApConfiguration.Invoke(wifiManager);
                    return("{\"wifi\": true, \"ssid\": \"" + config.Ssid + "\",\"ip\": \"unknown\"}");
                }
                else
                {
                    return("{\"wifi\": false}");
                }
            }
        }
示例#17
0
        public void Connect(string ssid, string passphrase = null)
        {
            var conf = new WifiConfiguration
            {
                Ssid = $"\"{ssid}\""
            };

            // very important for unprotected networks otherwise connection doesn't go on
            if (passphrase == null)
            {
                conf.AllowedKeyManagement.Set((int)KeyManagementType.None);
            }
            else
            {
                conf.AllowedKeyManagement.Set((int)KeyManagementType.WpaPsk);
                conf.PreSharedKey = $"\"{passphrase}\"";
            }

            var netId = Wifi.AddNetwork(conf);

            currentNetwork = Wifi.ConnectionInfo.NetworkId;
            Wifi.Disconnect();
            var connected = Wifi.EnableNetwork(netId, true);

            if (connected)
            {
                Wifi.Reconnect();
            }
        }
示例#18
0
        public async Task <WiFiInfo> ConnectPreferredWifi()
        {
            WiFiInfo w = null;

            var wifiMgr           = (WifiManager)context.GetSystemService(Context.WifiService);
            var formattedSsid     = $"\"{preferredWifi}\"";
            var formattedPassword = $"\"{prefferedWifiPassword}\"";

            bool wifiEnabled = await SetWifiOn();

            if (wifiEnabled)
            {
                w = await GetConnectedWifi(true);

                if (w == null || w.SSID != formattedSsid)
                {
                    //no wifi is connected or other wifi is connected
                    if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.Q)
                    {
                        //Android 10 and later
                        //string bssid = await GetBestBSSID();
                        string status = await SuggestNetwork();

                        w = await GetConnectedWifi(true);
                    }
                    else
                    {
                        //Android 9 and earlier
                        var wifiConfig = new WifiConfiguration
                        {
                            Ssid         = formattedSsid,
                            PreSharedKey = formattedPassword
                        };
                        var addNetwork = wifiMgr.AddNetwork(wifiConfig);
                        var network    = wifiMgr.ConfiguredNetworks.FirstOrDefault(n => n.Ssid == formattedSsid);

                        if (network == null)
                        {
                            w = null;
                        }
                        else
                        {
                            if (w.SSID != formattedSsid && w.SSID != "<unknown ssid>")
                            {
                                wifiMgr.Disconnect();
                            }
                            var enableNetwork = wifiMgr.EnableNetwork(network.NetworkId, true);
                            wifiMgr.Reconnect();
                        }
                    }
                    throw new NoPreferredConnectionException();
                }
            }
            else
            {
                throw new WifiTurnedOffException();
            }

            return(w);
        }
示例#19
0
        private void OnConnetti4ButtonClicked(object sender, EventArgs e)
        {
            Models.Device     device      = (Models.Device)BindingContext;
            WifiConfiguration conf        = new WifiConfiguration();
            WifiManager       wifiManager = (WifiManager)Android.App.Application.Context
                                            .GetSystemService(Context.WifiService);

            conf.Ssid         = string.Format("\"{0}\"", device.Ssid);
            conf.PreSharedKey = string.Format("\"{0}\"", device.WifiPwd);



            IList <WifiConfiguration> wifiConfigurationList = wifiManager.ConfiguredNetworks;

            foreach (WifiConfiguration removeConfig in wifiConfigurationList)
            {
                if (removeConfig.Ssid.Equals(conf.Ssid))
                {
                    wifiManager.RemoveNetwork(removeConfig.NetworkId);
                    break;
                }
            }
            int netId = wifiManager.AddNetwork(conf);

            test_4.Text = Convert.ToString(wifiManager.ConnectionInfo.NetworkId);
            //wifiManager.DisableNetwork(wifiManager.ConnectionInfo.NetworkId);
            wifiManager.EnableNetwork(netId, true);
        }
示例#20
0
        public void ConnectToWifi(string ssid, string password)
        {
            var wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);

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

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

            var addNetwork = wifiManager.AddNetwork(wifiConfig);

            var network = wifiManager.ConfiguredNetworks
                          .FirstOrDefault(n => n.Ssid == $"\"{ssid}\"");


            if (network == null)
            {
                throw new Exception($"Não foi possível conectar a rede: {ssid}");
            }

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

            wifiManager.Reconnect();
        }
示例#21
0
        public async void ConnectToWifi(string ssid, string password)
        {
            if (Android.OS.Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.Q)
            {
                var formattedSsid     = $"\"{ssid}\"";
                var formattedPassword = $"\"{password}\"";

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

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

                var addNetwork = wifiManager.AddNetwork(wifiConfig);
                var network    = new WifiConfiguration();

                IList <Android.Net.Wifi.WifiConfiguration> networks = wifiManager.ConfiguredNetworks.ToList <WifiConfiguration>();
                foreach (var n in networks)
                {
                    Console.WriteLine($"Config Networks: {n.Bssid}");
                    if (n.Ssid == formattedSsid)
                    {
                        network = n;
                    }
                }

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

                wifiManager.Disconnect();
                var enableNetwork = wifiManager.EnableNetwork(network.NetworkId, true);
                wifiManager.Reconnect();

                await Application.Current.MainPage.DisplayAlert("Failed to connect", ssid, "OK");
            }
            else
            {
                WifiNetworkSpecifier.Builder builder          = new WifiNetworkSpecifier.Builder();
                WifiNetworkSpecifier         networkSpecifier = builder
                                                                .SetSsid(ssid)
                                                                .SetWpa2Passphrase(password)
                                                                .Build();

                NetworkRequest.Builder networkRequest = new NetworkRequest.Builder();
                networkRequest
                .SetNetworkSpecifier(networkSpecifier)
                .Build();

                ConnectivityManager connectivityManager = (ConnectivityManager)Android.App.Application.Context.GetSystemService(Context.ConnectivityService);

                NetworkCallback networkCallback = new NetworkCallback(connectivityManager);
            }
        }
示例#22
0
        public override void OnReceive(Context context, Intent intent)
        {
            string       action   = intent.Action;
            const string ssid     = "\"sound_reactive\"";
            const string password = "******"password\"";

            if (WifiManager.ScanResultsAvailableAction.Equals(action))
            {
                List <ScanResult> wifiList = wifiManager
                                             .ScanResults.ToList();

                WifiConfiguration network = wifiList
                                            .Where(x => x.Ssid.Equals("sound_reactive"))
                                            .Select(x => new WifiConfiguration()
                {
                    Ssid = "sound_reactive"
                })
                                            .FirstOrDefault();

                if (network != null)
                {
                    network.PreSharedKey = password;
                    network.Ssid         = ssid;
                    wifiList.ForEach(x => {
                        if (x.Ssid != "sound_reactive")
                        {
                            WifiConfiguration wifi =
                                new WifiConfiguration()
                            {
                                Ssid = x.Ssid
                            };

                            wifiManager.DisableNetwork(wifi.NetworkId);
                        }
                    });

                    wifiManager.EnableNetwork(network.NetworkId, true);

                    if (wifiManager.Reconnect())
                    {
                        Intent redirectToMainControl =
                            new Intent(context, typeof(MainControlActivity));

                        context.StartActivity(redirectToMainControl);
                    }
                }
                else
                {
                    AlertDialog.Builder builder =
                        new AlertDialog.Builder(context);

                    builder.SetMessage("Not found");
                    AlertDialog alert = builder.Create();
                    alert.Show();
                }
            }

            context.UnregisterReceiver(this);
        }
示例#23
0
        private void Connect(string SSID, string sharedKey)
        {
            // return early
            if (_tryingToConnect == true)
            {
                return;
            }

            try
            {
                _tryingToConnect = true;

                if (_wifiManager != null)
                {
                    // if already connected then no need to connect
                    if (_wifiManager.ConnectionInfo != null && _wifiManager.ConnectionInfo.SSID == SSID)
                    {
                        Connected = true;
                    }
                    else
                    {
                        WifiConfiguration wifiConfig = new WifiConfiguration();
                        wifiConfig.Ssid         = String.Format("\"{0}\"", SSID);
                        wifiConfig.PreSharedKey = String.Format("\"{0}\"", sharedKey);

                        // Get or add network to known list.
                        int netId = GetOrAddNetworkId(SSID, wifiConfig);

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

                        // if connected and not connected to network needed then disconnect and reconnect
                        if (_wifiManager.ConnectionInfo != null && _wifiManager.ConnectionInfo.NetworkId != netId)
                        {
                            _wifiManager.Disconnect();
                            _wifiManager.EnableNetwork(netId, true);
                            _wifiManager.Reconnect();
                        }

                        if (_wifiManager.ConnectionInfo != null && _wifiManager.ConnectionInfo.SSID == SSID && _wifiManager.ConnectionInfo.SupplicantState == SupplicantState.Completed)
                        {
                            Connected = true;
                        }
                        else
                        {
                            Connected = false;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Connected = false;
            }
            finally
            {
                _tryingToConnect = false;
            }
        }
示例#24
0
        public async Task <bool> ConnectToWifi(WifiCredentials credentials)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            var tcs = new TaskCompletionSource <bool>();

#pragma warning disable 4014
            Task.Run(async() =>
            {
                try
                {
                    var wifiConfig = new WifiConfiguration
                    {
                        Ssid         = $"\"{credentials.Ssid}\"",
                        PreSharedKey = $"\"{credentials.Pwd}\""
                    };

                    WifiManager wifiManager = (WifiManager)_context.GetSystemService(Context.WifiService);

                    // Use ID
                    int netId = wifiManager.AddNetwork(wifiConfig);
                    wifiManager.Disconnect();
                    await Task.Delay(1000);
                    int disconnectedIp = wifiManager.ConnectionInfo?.IpAddress ?? 0;
                    int currentIp      = disconnectedIp;
                    wifiManager.EnableNetwork(netId, true);
                    wifiManager.Reconnect();

                    for (int i = 0; i < 100; i++)
                    {
                        currentIp = wifiManager.ConnectionInfo?.IpAddress ?? 0;
                        if (currentIp != disconnectedIp)
                        {
                            await Task.Delay(1000);
                            break;
                        }
                        else
                        {
                            await Task.Delay(250);
                        }
                    }

                    tcs.SetResult(currentIp != disconnectedIp);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.ToString());
                    Debugger.Break();
                    tcs.SetResult(false);
                }
            });
#pragma warning restore 4014

            return(await tcs.Task);
        }
示例#25
0
        public void ConnectToWifi(string ssid, string password)
        {
            var formattedSsid     = $"\"{ssid}\"";
            var formattedPassword = $"\"{password}\"";

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

            try
            {
                var addNetwork = _wifiManager.AddNetwork(wifiConfig);
            }
            catch (Exception ex)
            {
                OnError?.Invoke(new Exception("WifiConnector can not add the new wifi network configuration", ex));
            }

            WifiConfiguration network = null;

            try
            {
                network = _wifiManager.ConfiguredNetworks
                          .FirstOrDefault(n => n.Ssid == formattedSsid);

                if (network == null)
                {
                    OnError?.Invoke(new Exception("WifiConnector can not connect to the specified wifi network"));
                    return;
                }
            }
            catch (Exception ex)
            {
                OnError?.Invoke(new Exception("WifiConnector can not get the list of configured wifi networks", ex));
                return;
            }

            try
            {
                _wifiManager.Disconnect();
                var enableNetwork = _wifiManager.EnableNetwork(network.NetworkId, true);
                if (enableNetwork && _wifiManager.ConnectionInfo != null && _wifiManager.ConnectionInfo.SSID.Equals(formattedSsid))
                {
                    OnLog?.Invoke("WiFi network has been connected");
                }
                else
                {
                    OnError?.Invoke(new Exception("Te specified wifi network does not exist"));
                }
            }
            catch (Exception ex)
            {
                OnError?.Invoke(new Exception("Activating the connection to the configured wifi network failed", ex));
            }
        }
示例#26
0
        public void ToggleWifiHotspot(bool On)
        {
            Method[] methods = _manager.Class.GetDeclaredMethods();
            Boolean  enabled = false;

            foreach (Method method in methods)
            {
                if (method.Name.Equals("isWifiEnabled"))
                {
                    enabled = (Boolean)method.Invoke(_manager);
                }
                if (method.Name.Equals("getWifiApConfiguration"))
                {
                    try {
                        config              = (WifiConfiguration)method.Invoke(_manager, null);
                        config.Ssid         = "liteshare";
                        config.PreSharedKey = GenerateRandomPassword(8);
                    } catch (Exception e) {
                        Log.Error("WifiServiceImplementation", "Error chagning network settings\n" + e.Message);
                    }
                }
            }

            // if hotspot is not enabled and the method received True, turn on hotspot
            if (On && !enabled)
            {
                foreach (Method method in methods)
                {
                    if (method.Equals("setWifiApEnabled"))
                    {
                        try {
                            method.Invoke(_manager, config, true);
                        } catch (Exception e) {
                            Log.Info("WifiServiceImplementation", "Error turning hotspot on\n" + e.Message);
                        }
                    }
                }
            }

            // if hotspot is enabled and the method received False, turn off hotspot
            else if (!On && enabled)
            {
                foreach (Method method in methods)
                {
                    if (method.Name.Equals("setWifiApEnabled"))
                    {
                        try {
                            method.Invoke(_manager, config, false);
                        } catch (Exception e) {
                            Log.Info("WifiServiceImplementaion", "Error turning hotspot off\n" + e.Message);
                        }
                    }
                }
            }
        }
        public void Connect(Models.WifiDescriptor descriptor, string passPhrase)
        {
            WifiConfiguration wifiConfig = new WifiConfiguration
            {
                Ssid         = $"\"{descriptor.Ssid}\"",
                PreSharedKey = $"\"{passPhrase}\""
            };

            try
            {
                this._wifiManager.AddNetwork(wifiConfig);
            }
            catch (Exception ex)
            {
                throw new WifiException("WifiConnector can not add the new wifi network configuration", ex);
            }

            WifiConfiguration network = null;

            try
            {
                network = this._wifiManager.ConfiguredNetworks
                          .FirstOrDefault(n => n.Ssid == wifiConfig.Ssid);

                if (network == null)
                {
                    throw new WifiException("WifiConnector can not connect to the specified wifi network");
                }
            }
            catch (Exception ex)
            {
                throw new WifiException("WifiConnector can not get the list of configured wifi networks", ex);
            }

            try
            {
                this._wifiManager.Disconnect();

                bool networkEnabled = _wifiManager.EnableNetwork(network.NetworkId, true);

                if (this.VerifyConnectivity(wifiConfig.Ssid, networkEnabled))
                {
                    OnConnected?.Invoke(this, EventArgs.Empty);
                }
                else
                {
                    throw new WifiException("The specified wifi network does not exist");
                }
            }
            catch (Exception ex)
            {
                throw new WifiException("Activating the connection to the configured wifi network failed", ex);
            }
        }
示例#28
0
 private void SetWifiApConfiguration(WifiConfiguration wifiConfig)
 {
     try
     {
         var method = _wifiManager.Class.GetMethod("setWifiApConfiguration", Class.FromType(typeof(WifiConfiguration)));
         method.Invoke(_wifiManager, wifiConfig);
     }
     catch (Exception ex)
     {
         throw new Exception("HotspotCreator can not configure a hotspot network", ex);
     }
 }
        public void ConnectToWifi()
        {
            var config = new WifiConfiguration();

            config.Ssid         = '"' + _wifiSsid + '"';
            config.PreSharedKey = '"' + _wifiPassword + '"';
            int id = _wifiManager.AddNetwork(config);

            _wifiManager.Disconnect();
            _wifiManager.EnableNetwork(id, true);
            _wifiManager.Reconnect();
        }
 /// <summary>
 /// Sets the Wi-Fi AP Configuration
 /// </summary>
 /// <param name="wifiConfig">The <see cref="WifiConfiguration"/></param>
 /// <returns><code>true</code> if the operation succeeded, <code>false</code> otherwise</returns>
 public bool SetWifiApConfiguration(WifiConfiguration wifiConfig)
 {
     try
     {
         Method method = wifiManager.Class.GetMethod("setWifiApConfiguration", Class.FromType(typeof(WifiConfiguration)));
         return((bool)method.Invoke(wifiManager, wifiConfig));
     }
     catch (System.Exception ex)
     {
         Log.Error(nameof(WifiApManager), "", ex);
         return(false);
     }
 }