[英]How to get the connected SSID in Xamarin.Forms?
I need to get the SSID of the current network that I am connected to.我需要获取我连接到的当前网络的SSID 。
Here is the code I used to find the SSID in Xamarin.Android :这是我用来在 Xamarin.Android 中查找SSID 的代码:
WifiManager wifiManager = (WifiManager)(Application.Context.GetSystemService(WifiService));
if (wifiManager != null)
{
var ssid = wifiManager.ConnectionInfo.SSID;
}
else
{
var str = "WiFiManager is NULL";
}
But I need to implement this in Xamarin.Forms .但我需要在Xamarin.Forms 中实现它。
How can I do this ?我怎样才能做到这一点 ?
You can use DependencyService .您可以使用DependencyService 。
The DependencyService class is a service locator that enables Xamarin.Forms applications to invoke native platform functionality from shared code.
DependencyService 类是一个服务定位器,它使 Xamarin.Forms 应用程序能够从共享代码调用本机平台功能。
1º Create a public interface (for organization sake, maybe under Mobile > Services > IGetSSID
) 1º创建一个公共接口(为了组织,可能在
Mobile > Services > IGetSSID
)
public interface IGetSSID
{
string GetSSID();
}
2º Create the Android Implementation 2º创建 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";
}
}
}
}
3º Then in your forms you get the SSID like this: 3º然后在你的表格中你会得到这样的 SSID:
var ssid = DependencyService.Get<IGetSSID>().GetSSID();
Note: Don't forget to add this permission on your Android Manifest注意:不要忘记在您的 Android 清单中添加此权限
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Required permissions: CHANGE_NETWORK_STATE, ACCESS_FINE_LOCATION所需权限:CHANGE_NETWORK_STATE、ACCESS_FINE_LOCATION
protected override void OnStart()
{
base.OnStart();
NetworkRequest request = new NetworkRequest.Builder().AddTransportType(transportType: TransportType.Wifi).Build();
ConnectivityManager connectivityManager = context.GetSystemService(Context.ConnectivityService) as ConnectivityManager;
int flagIncludeLocationInfo = (int)NetworkCallbackFlags.IncludeLocationInfo;
NetworkCallback networkCallback = new NetworkCallback(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)
{
var ssid = wifiInfo.SSID;
var bssid = wifiInfo.BSSID;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.