对于互联网检查,我写了下面的代码行。
bool isAvailable = NetworkInterface.GetIsNetworkAvailable();
if (isAvailable == true)
{
}
如果网络不可用,上面的行总是返回true。请告诉我如何检查互联网连接?
答案 0 :(得分:2)
检查 NetworkInterfaceType 。如果互联网可用,那么它 应该不是无
return (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType
!= Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None);
参考答案vjsrinath : https://stackoverflow.com/questions/8341169/how-to-check-internetconnection-in-wp7
希望这有帮助。
答案 1 :(得分:1)
你也可以尝试,
bool isAvailable = Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsNetworkAvailable;
答案 2 :(得分: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;
}
答案 3 :(得分:0)
检查UI线程中的NetworkInterface.NetworkInterfaceType
是“危险的”,因为它是一个阻塞调用!这次通话可能需要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