检查Xamarin Android应用是否已连接到两个网络中的一个

时间:2017-04-19 12:28:55

标签: c# networking xamarin network-programming detection

我正在编写一个Xamarin Android应用程序,我希望能够通过一个事件知道用户从网络(网络1)跳到另一个网络(网络2)并在病房之后处理一些逻辑。我遇到了这个插件https://github.com/jamesmontemagno/ConnectivityPlugin,但问题是,插件可能会触发我不监控的网络接口上的事件,我不想这样。我想知道如何实现这个目标?

谢谢

1 个答案:

答案 0 :(得分:1)

您可以通过Android BroadcastReceiver跟踪网络更改,这是一个快速示例,可跟踪您可以自定义以满足您的需求的wifi SSIS更改。

[BroadcastReceiver]
[IntentFilter(new string[] { WifiManager.NetworkStateChangedAction, WifiManager.WifiStateChangedAction })]
public class NetworkBroadcastReceiver : BroadcastReceiver
{
    readonly WifiManager wifiManager;
    public static string LastSSID;

    public NetworkBroadcastReceiver(IntPtr javaReference, Android.Runtime.JniHandleOwnership transfer) : base(javaReference, transfer)
    {
        wifiManager = (WifiManager)Application.Context.GetSystemService(Context.WifiService);
    }

    public NetworkBroadcastReceiver()
    {
        wifiManager = (WifiManager)Application.Context.GetSystemService(Context.WifiService);
    }

    public override void OnReceive(Context context, Intent intent)
    {
        string currentSSID = null;
        if (WifiManager.NetworkStateChangedAction == intent.Action)
        {
            var netInfo = (NetworkInfo)intent.GetParcelableExtra(WifiManager.ExtraNetworkInfo);
            var netInfoDetailed = netInfo.GetDetailedState();
            if (netInfo.IsConnected || netInfoDetailed == NetworkInfo.DetailedState.Connected) 
            {
                currentSSID = wifiManager.ConnectionInfo.SSID;
            }
            else if (!netInfo.IsConnected)
            {
                currentSSID = null;
            }
        }
        if (WifiManager.WifiStateChangedAction == intent.Action)
        {
            currentSSID = GetCurrentSSID();
        }
        if (LastSSID != currentSSID)
        {
            // Do something on SSID change....
            Toast.MakeText(context, $"Wireless SSID changed, from:{LastSSID} to:{currentSSID}", ToastLength.Long).Show();
            LastSSID = currentSSID;
        }
    }

    public static string GetCurrentSSID()
    {
        var wifiManager = (WifiManager)Application.Context.GetSystemService(Context.WifiService);
        if (wifiManager.ConnectionInfo.SupplicantState == SupplicantState.Completed)
        {
            return wifiManager.ConnectionInfo.SSID;
        }
        return null;
    }
}

注意:确保您已为清单添加权限(ACCESS_WIFI_STATEACCESS_NETWORK_STATE

如果需要,您可以通过调用以下方式在应用启动中设置初始跟踪SSID:

NetworkBroadcastReceiver.LastSSID = NetworkBroadcastReceiver.GetCurrentSSID();

或者只是通过以下方式检索当前的SSID:

var ssid = NetworkBroadcastReceiver.GetCurrentSSID();