如何获取Xamarin.Forms中连接的SSID?

How to get the connected SSID in Xamarin.Forms?

我需要获取我当前连接的网络的SSID

这是我用来在 Xamarin.Android 中查找 SSID 的代码:

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

if (wifiManager != null)
{
    var ssid =  wifiManager.ConnectionInfo.SSID;
}
else
{
    var str =  "WiFiManager is NULL";
}

但是我需要在Xamarin.Forms中实现这个。

我该怎么做?

您可以使用 DependencyService.

The DependencyService class is a service locator that enables Xamarin.Forms applications to invoke native platform functionality from shared code.

创建一个 public 接口(为了组织起见,可能在 Mobile > Services > IGetSSID 下)

public interface IGetSSID
{
    string GetSSID();
}

创建 Android 实现

[assembly: Dependency(typeof(GetSSIDAndroid))]
namespace yournamespace
{
    public class GetSSIDAndroid : IGetSSID
    {
        public 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";
            }
        }
    }
}

然后在你的表格中你会得到这样的 SSID:

var ssid = DependencyService.Get<IGetSSID>().GetSSID();

注意:不要忘记在您的 Android Manifest

中添加此权限
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

获取 SSID 和 BSSID API31 Xamarin C# 示例

所需权限:CHANGE_NETWORK_STATE、ACCESS_FINE_LOCATION

如果 API<31 TransportInfo 将 return Null

using Android.Content;
using Android.Net;
using Android.Net.Wifi;

protected override void OnStart()
    {
        base.OnStart();

        NetworkRequest request = new NetworkRequest.Builder().AddTransportType(transportType: TransportType.Wifi).Build();
        ConnectivityManager connectivityManager = Android.App.Application.Context.GetSystemService(Context.ConnectivityService) as ConnectivityManager;

        NetworkCallbackFlags flagIncludeLocationInfo = NetworkCallbackFlags.IncludeLocationInfo;
        NetworkCallback networkCallback = new NetworkCallback((int)flagIncludeLocationInfo);
        connectivityManager.RequestNetwork(request, networkCallback);
    }

    private class NetworkCallback : ConnectivityManager.NetworkCallback
    {
        public NetworkCallback(int flags) : base(flags)
        {
        }

        public override void OnCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities)
        {
            base.OnCapabilitiesChanged(network, networkCapabilities);
            WifiInfo wifiInfo = (WifiInfo)networkCapabilities.TransportInfo;

            if (wifiInfo != null)
            {
                string ssid = wifiInfo.SSID.Trim(new char[] {'"', '\"' });
                string bssid = wifiInfo.BSSID;
            }
        }
    }

点击Android API reference.ConnectivityManager.NetworkCallback(int)!