我试图为Windows手机制作一个笑话应用。该应用程序从互联网上获取笑话,所以,我希望它能够检查wifi信号或能够连接到互联网。我将如何创建它?
答案 0 :(得分:2)
在WP8.1运行时,您可以从NetworkInformation
类查询大部分内容,如下所示:
// need this namespace
using Windows.Networking.Connectivity;
bool is_wifi_connected = false;
ConnectionProfile current_connection_for_internet = NetworkInformation.GetInternetConnectionProfile();
if (current_connection_for_internet.IsWlanConnectionProfile)
{
if (current_connection_for_internet.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess)
{
is_wifi_connected = true;
}
}
WP8.0您可以像NetworkInterfaceList
那样查询大部分内容:
// see is wifi is ON and connected
using Microsoft.Phone.Net.NetworkInformation;
bool is_wifi_connected = false;
if (NetworkInterface.GetIsNetworkAvailable())
{
NetworkInterfaceList nif = new NetworkInterfaceList();
foreach(NetworkInterfaceInfo item in nif)
{
if (item.InterfaceSubtype == NetworkInterfaceSubType.WiFi && item.InterfaceState == ConnectState.Connected)
{
is_wifi_connected = true;
}
}
}
现在看看它是否可以连接到网站只需打开一个连接。您可以使用任何您喜欢的网络连接。只需在下载文件时使用WebClient和事件处理程序执行此操作。
using System.Net;
// check network and is_wifi_connected
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() && is_wifi_connected)
{
WebClient downloader = new WebClient();
Uri uri = new Uri("http://www.google.com", UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadDone);
downloader.DownloadStringAsync(uri);
}
void DownloadDone(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("There was an error downloading the site.");
}
else
{
// your html file or what not is stored here
string content = e.Result;
}
}