How to know the wifi SSID my device is connected to in Xamarin?

1.1k Views Asked by At

I have an app that needs to be connected to a specific network. I already have a code to force the device to connect to that network, but every time I open a different screen it repeats the process and it takes like 2 or 3 seconds. So, instead of forcing to connect every time I want to ask in what network it is in that moment, so, if it's the incorrect network it has to connect to the correct one, and if it's in the correct one it doesn't have to do anything. How can I get the network's name?

Below is the code I am using, but when I debug it it says the SSID name is "<unknown ssid>", so every time I check if the name is correct it says that is false and it connects again to the network.

public static string GetSSID() {

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

        if (wifiManager != null && !string.IsNullOrEmpty(wifiManager.ConnectionInfo.SSID))
        {
            return wifiManager.ConnectionInfo.SSID;
        }
        else
        {
            return "WiFiManager is NULL";
        }
    }
1

There are 1 best solutions below

2
Liyun Zhang - MSFT On

At first, you need to grant the app the permission about the location.

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

And then you need to grant the permisson by the ActivityCompat.RequestPermissions before you get the information of the wifi.

The official document about run-time permission: https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/permissions?tabs=windows

In addition, you can also try the following code to get the SSID after the permission granting.

 ConnectivityManager connectivityManager = (ConnectivityManager)Android.App.Application.Context.GetSystemService(Context.ConnectivityService);
 NetworkInfo networkInfo = connectivityManager.ActiveNetworkInfo;
 var ssid = networkInfo.ExtraInfo;