我的应用WP7未被接受,因为如果互联网不可用,则无法加载。我找了一种检查它的方法并找到了这个命令
NetworkInterface.GetIsNetworkAvailable()
但它不能在模拟器上运行,我没有任何设备可以测试它。 如果设备处于飞行模式,有人可以告诉我它是否返回false?如果没有,我该如何检查呢?
谢谢, 奥斯卡
编辑:我也试过这段代码:
try
{
wsClient.CurrenciesCompleted += new EventHandler<CurrencyConversion.CurrenciesCompletedEventArgs>(wsClient_CurrenciesCompleted);
wsClient.CurrenciesAsync(null);
}
catch
{
NetworkNotAvailable();
}
但是我无法捕捉异常,我也尝试过wsClient_CurrenciesCompleted方法,但也没有好处。
我可以在哪里测试它?
答案 0 :(得分:6)
不要测试“一般的互联网” - 测试您实际连接的服务。通过尝试连接来测试它 - 在启动时做一些简单的非破坏性请求。是的,这将占用用户数据的一小部分,但是:
答案 1 :(得分:3)
Jon建议的替代方案是检查哪个网络接口可用。如果您需要根据网络速度调整您调用的服务,这非常方便。例如,可以修改下面的switch语句以返回Enum来表示网络的质量。
public class NetworkMonitorClass
{
private Timer timer;
private NetworkInterfaceType _currNetType = null;
private volatile bool _valueRetrieved = false;
public NetworkMonitorClass()
{
//using a timer to poll the network type.
timer = new Timer(new TimerCallBack((o)=>
{
//Copied comment from Microsoft Example:
// Checking the network type is not instantaneous
// so it is advised to always do it on a background thread.
_currNetType = Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType;
_valueRetrieved = true;
}), null, 200, 3000); // update the network type every 3 seconds.
}
public NetworkInterfaceType CurrentNetworkType
{
get
{
if(false == _valueRetrieved ) return NetworkInterfaceType.Unknown;
return _currNetType;
}
private set { ;}
}
public bool isNetworkReady()
{
if(false == _valueRetrieved ) return false;
switch (_currentNetworkType)
{
//Low speed networks
case NetworkInterfaceType.MobileBroadbandCdma:
case NetworkInterfaceType.MobileBroadbandGsm:
return true;
//High speed networks
case NetworkInterfaceType.Wireless80211:
case NetworkInterfaceType.Ethernet:
return true;
//No Network
case NetworkInterfaceType.None:
default:
return false;
}
}
}
答案 2 :(得分:2)
GetIsNetworkAvailable()
将始终在模拟器中返回true。要在模拟器中进行测试,您需要在代码中进行此操作。
这可以是一个有用的快速检查,但您也(如Jon指出的那样)需要处理无法连接到您的特定服务器的情况。
当您尝试在回调中获取响应时,可以通过捕获WebException来完成此操作。
private static void DownloadInfoCallback(IAsyncResult asynchronousResult)
{
try
{
var webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// This will cause an error if the request failed
var webResponse = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
.....
}
catch (WebException exc)
{
// Handle error here
}
}
答案 3 :(得分:0)
GetIsNetworkAvailable()在设备上正常运行。
您可以使用Microsoft.Devices.Environment.DeviceType模拟处理此操作以在模拟器中进行测试。
我倾向于通过异常处理测试互联网的可用性和网站的可用性,并向应用程序的用户提供反馈,指出功能不可用的真正原因。