如何检查Windows Phone 8应用程序中的Internet连接可用性
我正在开发Windows Phone 8应用程序 。 在这个应用程序中,我必须连接到服务器以获取数据。
所以在连接到服务器之前,我想检查互联网连接是否可用于设备。 如果互联网连接可用,那么我只会从服务器获取数据,否则我将显示错误消息。
请告诉我如何在Windows Phone 8中执行此操作。
NetworkInterface.GetIsNetworkAvailable()
返回NIC的状态。
根据状态,您可以通过使用以下方式询问是否建立了连接:
ConnectionProfile
– 使用enum NetworkConnectivityLevel
的Windows Phone 8.1类:
- 没有
- 本地访问
- 互联网
这段代码应该可以解决问题。
bool isConnected = NetworkInterface.GetIsNetworkAvailable(); if (isConnected) { ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile(); NetworkConnectivityLevel connection = InternetConnectionProfile.GetNetworkConnectivityLevel(); if (connection == NetworkConnectivityLevel.None || connection == NetworkConnectivityLevel.LocalAccess) { isConnected = false; } } if(!isConnected) await new MessageDialog("No internet connection is avaliable. The full functionality of the app isn't avaliable.").ShowAsync();
public static bool checkNetworkConnection() { var ni = NetworkInterface.NetworkInterfaceType; bool IsConnected = false; if ((ni == NetworkInterfaceType.Wireless80211)|| (ni == NetworkInterfaceType.MobileBroadbandCdma)|| (ni == NetworkInterfaceType.MobileBroadbandGsm)) IsConnected= true; else if (ni == NetworkInterfaceType.None) IsConnected= false; return IsConnected; }
调用此function并检查互联网连接是否可用。
您可以使用NetworkInterface.GetIsNetworkAvailable()
方法。 如果网络连接可用则返回true,否则返回false。 如果您在PCL中,请不要忘记using Microsoft.Phone.Net.NetworkInformation
或using System.Net.NetworkInformation
添加。
由于这个问题出现在谷歌搜索检查互联网可用性的第一个结果,我会把Windows Phone 8.1 XAML的答案。 与8相比,它有一些不同的API。
//Get the Internet connection profile string connectionProfileInfo = string.Empty; try { ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile(); if (InternetConnectionProfile == null) { NotifyUser("Not connected to Internet\n"); } else { connectionProfileInfo = GetConnectionProfile(InternetConnectionProfile); NotifyUser("Internet connection profile = " +connectionProfileInfo); } } catch (Exception ex) { NotifyUser("Unexpected exception occurred: " + ex.ToString()); }
有关更多阅读,请访问MSDN如何检索网络连接…
您可以使用NetworkInformation.GetInternetConnectionProfile
来获取当前正在使用的配置文件,从中可以计算出连接级别。 更多信息GetInternetConnectionProfile msdn
您可以如何使用的示例。
private void YourMethod() { if (InternetConnection) { // Your code connecting to server } } public static bool InternetConnection() { return NetworkInformation.GetInternetConnectionProfile().GetNetworkConnectivityLevel() >= NetworkConnectivityLevel.InternetAccess; }
这就是我做的…
class Internet { static DispatcherTimer dispatcherTimer; public static bool Available = false; public static async void StartChecking() { dispatcherTimer = new DispatcherTimer(); dispatcherTimer.Tick += new EventHandler(IsInternetAvailable1); dispatcherTimer.Interval = new TimeSpan(0, 0, 10); //10 Secconds or Faster await IsInternetAvailable(null, null); dispatcherTimer.Start(); } private static async void IsInternetAvailable1(object sender, EventArgs e) { await IsInternetAvailable(sender, e); } private static async Task IsInternetAvailable(object sender, EventArgs ev) { string url = "https://www.google.com/"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "text/plain; charset=utf-8"; httpWebRequest.Method = "POST"; using (var stream = await Task.Factory.FromAsync(httpWebRequest.BeginGetRequestStream, httpWebRequest.EndGetRequestStream, null)) { string json = "{ \"302000001\" }"; //Post Anything byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json); await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length); WebClient hc = new WebClient(); hc.DownloadStringCompleted += (s, e) => { try { if (!string.IsNullOrEmpty(e.Result)) { Available = true; } else { Available = false; } } catch (Exception ex) { if (ex is TargetInvocationException) { Available = false; } } }; hc.DownloadStringAsync(new Uri(url)); } } }
由于Windows Phone 8无法检查互联网连接,因此您需要通过发送POST HTTP请求来实现。 您可以通过将其发送到您想要的任何网站来实现。 我选择了google.com。 然后,每10秒或更短时间检查一次以刷新连接状态。
Web请求的响应可能会有一些延迟。 因此,对于某些应用来说,这种方法可能不够快。 这将检查任何设备上的互联网连接。 更好的方法是检查始终在线网站的端口80(http流量的默认端口)。
public static bool TcpSocketTest() { try { System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient("www.google.com", 80); client.Close(); return true; } catch (System.Exception ex) { return false; } }