2012-06-22 78 views
3

對於互聯網檢查我寫了下面的代碼行。如何檢查互聯網是否可用在Windows Phone 7中?

bool isAvailable = NetworkInterface.GetIsNetworkAvailable(); 
      if (isAvailable == true) 
      { 
} 

如果網絡不可用,上述行總是返回true。請告訴我如何檢查互聯網連接?

+0

,您僅在模擬器上進行測試呢?如果是這樣,請參閱[這裏](http://www.codebadger.com/blog/post/2010/11/16/WP7-Development-Tip-of-the-Day-Checking-for-an-internet-connection。 aspx) – benjer3

+0

[WP7檢查互聯網是否可用]的可能重複(http://stackoverflow.com/questions/4378456/wp7-check-if-internet-is-available) – ctacke

回答

1

您也可以嘗試,

bool isAvailable = Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsNetworkAvailable; 
+1

上述不具有蜂窩連接時。只有連接到wifi才能工作。 – Thierry

0
 Always check this in a thread, it takes some time   
    internal static bool IsNetworkAvailable() 
    { 
     bool _bhasNetworkConnection = false; 
     try 
     { 
      _bhasNetworkConnection = (NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None); 
     } 
     catch 
     { 
      _bhasNetworkConnection = false; 
     } 

     return _bhasNetworkConnection; 
    } 
0

檢查NetworkInterface.NetworkInterfaceType在UI線程是 「危險的」,因爲它是一個阻塞調用!這可能是此調用需要長達20秒......

使用下面的方法有無阻塞通話:

public static void IsConnected(Action<bool> completed) 
{ 
    ThreadPool.QueueUserWorkItem(o => 
    { 
     var type = NetworkInterface.NetworkInterfaceType; 
     completed(type != NetworkInterfaceType.None); 
    }); 
} 

https://xp-dev.com/svn/mytoolkit/MyToolkit.Wp8/Networking/NetworkState.cs從我的項目頁面

如果您想更改completed操作中的UI,您必須在UI線程中運行邏輯。例如: -

NetworkState.IsConnected(connected => { 
    if (connected) 
    { 
     Deployment.Current.Dispatcher.BeginInvoke(delegate { 
      // TODO add your UI logic 
     }); 
    } 
}); 

如果你需要大量的連接檢查,檢查出NetworkStateTracker,這是我的項目:

https://xp-dev.com/svn/mytoolkit/MyToolkit.Wp8/Networking/NetworkStateTracker.cs

相關問題