Last active
March 28, 2024 14:03
-
-
Save kraigspear/2c3de568cc7ae3c5c360bcac7e9db92a to your computer and use it in GitHub Desktop.
Connect to WIFI via code in Xamarin Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Android.App; | |
using Android.Content; | |
using Android.Net.Wifi; | |
using Android.Widget; | |
using Android.OS; | |
using Android.Runtime; | |
namespace App4 | |
{ | |
[Activity(Label = "App4", MainLauncher = true)] | |
public class MainActivity : Activity | |
{ | |
protected override void OnCreate(Bundle savedInstanceState) | |
{ | |
base.OnCreate(savedInstanceState); | |
// Set our view from the "main" layout resource | |
SetContentView(Resource.Layout.Main); | |
var connectButton = FindViewById<Button>(Resource.Id.connectButton); | |
connectButton.Click += ConnectButtonOnClick; | |
} | |
protected override void OnDestroy() | |
{ | |
var connectButton = FindViewById<Button>(Resource.Id.connectButton); | |
connectButton.Click -= ConnectButtonOnClick; | |
base.OnDestroy(); | |
} | |
private void ConnectButtonOnClick(object sender, EventArgs eventArgs) | |
{ | |
ConnectToWifi(); | |
} | |
private void ConnectToWifi() | |
{ | |
const string ssid = "\"ssid\""; | |
const string password = "\"password\""; | |
var wifiConfig = new WifiConfiguration | |
{ | |
Ssid = ssid, | |
PreSharedKey = password | |
}; | |
var wifiManager = GetSystemService(WifiService).JavaCast<WifiManager>(); | |
var addNetwork = wifiManager.AddNetwork(wifiConfig); | |
System.Diagnostics.Debug.WriteLine("addNetwork = " + addNetwork); | |
var network = wifiManager.ConfiguredNetworks.FirstOrDefault((n) => n.Ssid == ssid); | |
if (network == null) | |
{ | |
System.Diagnostics.Debug.WriteLine("Didn't find the network, not connecting."); | |
return; | |
} | |
wifiManager.Disconnect(); | |
var enableNetwork = wifiManager.EnableNetwork(network.NetworkId, true); | |
System.Diagnostics.Debug.WriteLine("enableNetwork = " + enableNetwork); | |
if (wifiManager.Reconnect()) | |
{ | |
var builder = new AlertDialog.Builder(this); | |
builder.SetMessage("Connected"); | |
var alert = builder.Create(); | |
alert.Show(); | |
} | |
else | |
{ | |
var builder = new AlertDialog.Builder(this); | |
builder.SetMessage("Nope"); | |
var alert = builder.Create(); | |
alert.Show(); | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment