是否可以使用Xamarin以编程方式连接到Wi-Fi网络?

时间:2016-03-01 17:37:17

标签: android ios xamarin

使用Xamarin.iOS和Xamarin.Android,可以检查是否启用了Wi-Fi? 并且,如果禁用,则可以启用它吗? 一旦启用,如何搜索并连接到网络?

1 个答案:

答案 0 :(得分:9)

启用/禁用Wifi:

WifiManager wifiManager = (WifiManager)GetSystemService(WifiService);
if (!wifiManager.IsWifiEnabled)
    wifiManager.SetWifiEnabled(true);
else 
    wifiManager.SetWifiEnabled(false);

更改Wifi状态的权限:

android.permission.CHANGE_WIFI_STATE

添加网络:

var networkSSID = "Stack";
var networkPass = "Overflow";
var config = new WifiConfiguration();
config.Ssid = '"' + networkSSID + '"';

// For WPA/WPA2, WEP is different (still using WEP? shame on you ;-)
config.PreSharedKey = '"' + networkPass + '"';
wifiManager.AddNetwork(config);

连接到网络:

IList<WifiConfiguration> myWifi = wifiManager.ConfiguredNetworks;
wifiManager.Disconnect();
wifiManager.EnableNetwork(myWifi.FindFirst(x => x.Ssid.Contains(networkSSID)), true);
wifiManager.Reconnect();