首先,如果你想知道在網絡連接的變化,你將要使用的DeviceNetworkInformation.NetworkAvailabilityChanged事件。
你不需要打開一個套接字,我建議迭代通過NetworkInterfaceList這是一個NetworkInterfaceInfo對象的集合。使用每個網絡接口查看它是否連接,以及是否查看它是什麼類型的網絡接口。以下是一些示例代碼:
NetworkStateTracker()
{
DetermineNetworkState();
DeviceNetworkInformation.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged;
}
void OnNetworkAvailabilityChanged(object sender, NetworkNotificationEventArgs args)
{
DetermineNetworkState();
}
void DetermineNetworkState()
{
bool bIsCellularConnected = false;
bool bIsWiFiConnected = false;
NetworkInterfaceList netInfoList = new NetworkInterfaceList();
foreach (NetworkInterfaceInfo netInfo in netInfoList)
{
if (netInfo.InterfaceState == ConnectState.Connected)
{
switch (netInfo.InterfaceType)
{
case NetworkInterfaceType.MobileBroadbandCdma:
case NetworkInterfaceType.MobileBroadbandGsm:
bIsCellularConnected = true;
break;
case NetworkInterfaceType.Wireless80211:
bIsWiFiConnected = true;
}
}
}
// Do something with the Network
}
但是 - 可能有多個連接可用 - 例如單元和wifi。 – WiredPrairie