我目前正在开发一个 WP8 应用程序,我已经为一个问题苦苦挣扎了大约一个月,
它是一个音乐播放器,它可以从远程 url 播放,但如果没有互联网连接,即 3g 或 wifi,并且播放列表中有一首歌曲,应用程序会意外崩溃
我想知道是否可以将其设置为在应用程序启动时检查网络状态,如果没有互联网连接,它会弹出一条通知说没有连接,然后关闭应用程序?如果可能的话,有人可以指出我从哪里开始的正确方向,
提前致谢
最佳答案
您可以使用 WebClient 从网站检索数据,使用 ping 或检查网络接口(interface)。
网络客户端
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new System.Uri("http://google.com"));
检查错误:
private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("An Error has occured. Maybe the website you are trying to reach is offline or you have no internetconnection");
});
}
}
平
public bool CheckInternetConnection()
{
bool success = false;
using (Ping ping = new Ping())
{
try
{
if (ping.Send("google.com", 2000).Status == IPStatus.Success)
{
success= true;
}
}
catch (PingException)
{
success = false;
}
}
return success;
}
检查网络接口(interface)
using Microsoft.Phone.Net.NetworkInformation;
private void CheckInetConnection()
{
if (NetworkInterface.GetIsNetworkAvailable() == true)
{
//Internet avalaible
}
else
{
//No connection available
}
}
您可以使用以下代码使用 C# 关闭应用:
Application.Current.Exit();
关于c# - WP8网络状态-无网络时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19448022/