using System; using Android.Content; using Android.Net.Wifi; namespace Shared.Net { public class WifiUtil { /* * 切换到指定wifi * @param wifiName 指定的wifi名字 * @param wifiPwd wifi密码,如果已经保存过密码,可以传入null * @return */ public void ConnectToWifi (Action action, string wifiName, string wifiPwd = null) { bool result = false; try { string tempWifiName = "\"" + wifiName + "\""; // 如果wifi权限没打开(1、先打开wifi,2,使用指定的wifi if (!mWifiManager.IsWifiEnabled) { if (!mWifiManager.SetWifiEnabled (true)) { return; } } var wifiList = mWifiManager.ConfiguredNetworks; var bFindInList = false; for (int i = 0; i < wifiList.Count; i++) { var wifiInfo0 = wifiList [i]; // 先找到对应的wifi if (tempWifiName == (wifiInfo0.Ssid) || wifiName == (wifiInfo0.Ssid)) { bFindInList = true; // 1、 先启动,可能已经输入过密码,可以直接启动 result = doChange2Wifi (wifiInfo0.NetworkId); } } // 2、如果wifi还没有输入过密码,尝试输入密码,启动wifi if (!bFindInList) { var wifiNewConfiguration = createWifiInfo (wifiName, wifiPwd);//使用wpa2的wifi加密方式 int newNetworkId = mWifiManager.AddNetwork (wifiNewConfiguration); if (newNetworkId == -1) { //Log.e (TAG, "操作失败,需要您到手机wifi列表中取消对设备连接的保存"); } else { result = doChange2Wifi (newNetworkId); } } } catch { } finally { if (action != null) action (result); } } bool doChange2Wifi (int newNetworkId) { var enableNetwork = mWifiManager.EnableNetwork (newNetworkId, true); if (!enableNetwork) { //"切换到指定wifi失败"; return false; } else { // "切换到指定wifi成功"; return true; } } /* * 创建 WifiConfiguration,这里创建的是wpa2加密方式的wifi * @param ssid wifi账号 * @param password wifi密码 * @return */ WifiConfiguration createWifiInfo (string ssid, string password) { var config = new WifiConfiguration (); config.AllowedAuthAlgorithms.Clear (); config.AllowedGroupCiphers.Clear (); config.AllowedKeyManagement.Clear (); config.AllowedPairwiseCiphers.Clear (); config.AllowedProtocols.Clear (); config.Ssid = "\"" + ssid + "\""; config.PreSharedKey = "\"" + password + "\""; config.AllowedAuthAlgorithms.Set ((int)WifiConfiguration.AuthAlgorithm.Open); config.AllowedGroupCiphers.Set ((int)WifiConfiguration.GroupCipher.Tkip); config.AllowedGroupCiphers.Set ((int)WifiConfiguration.GroupCipher.Ccmp); config.AllowedKeyManagement.Set ((int)WifiConfiguration.KeyMgmt.WpaPsk); config.AllowedPairwiseCiphers.Set ((int)WifiConfiguration.PairwiseCipher.Tkip); config.AllowedPairwiseCiphers.Set ((int)WifiConfiguration.PairwiseCipher.Ccmp); config.AllowedProtocols.Set ((int)WifiConfiguration.Protocol.Rsn); config.AllowedProtocols.Set ((int)WifiConfiguration.Protocol.Wpa); config.StatusField = WifiStatus.Enabled; return config; } WifiManager mWifiManager; // 单例 static WifiUtil ourInstance = new WifiUtil (); public static WifiUtil Instance { get { if (ourInstance.mWifiManager == null) { ourInstance.mWifiManager = (WifiManager)Shared.Application.Activity.GetSystemService (Context.WifiService); } return ourInstance; } } } }