c# - WP8网络状态-无网络时应用程序崩溃

标签 c# windows windows-phone-7 windows-phone-8

我目前正在开发一个 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/

相关文章:

c# - 使用 Swagger 的 Web API

python - 什么是更 Pythonic 的方法来测试我的部分代码?

css - 位置 :fixed in Windows Phone 7

c# - 从 Windows Phone 7 中的麦克风获取数据文件

windows-phone-7 - 磁贴标题的字体大小和系列

c# - 从网络驱动器连接/复制

c# - 带有 ASP.Net 按钮点击的弹出窗口未被弹出窗口拦截器阻止

c# - DataAdapter 不需要打开数据库连接?

python - 在 Python 中,如何获取文件的正确大小写路径?

windows - 写入多个文件与。写一个大文件[在固态驱动器中]