简体   繁体   English

C#:如何检查PCL项目中的Internet访问

[英]C#: How to check internet access in PCL project

I'm trying to check for an internet connection in a PCL project that is used by a Xamarin.iOS and Xamarin.Android projects. 我正在尝试检查Xamarin.iOS和Xamarin.Android项目使用的PCL项目中的Internet连接。 I'm gathering from my research that WebClient can't be used in a PCL, but I haven't been able to find a satisfactory solution that doesn't use WebClient. 我从研究中发现,WebClient不能在PCL中使用,但是我还没有找到一个不使用WebClient的令人满意的解决方案。 Here's the code I'd like to use: 这是我要使用的代码:

try
{
    using (var client = new WebClient())
    {
        using (var stream = client.OpenRead("http://www.google.com"))
        {
            return true;
        }
    }
}
catch
{
    return false;
}

Does anyone know of a good solution that is similarly simple? 有谁知道类似的简单好解决方案?

The easiest way is to use the Connectivity plugin from James Montemagno: 最简单的方法是使用James Montemagno的Connectivity插件:

https://github.com/jamesmontemagno/ConnectivityPlugin https://github.com/jamesmontemagno/ConnectivityPlugin

You install this, then call: 您安装此,然后调用:

CrossConnectivity.Current.IsConnected

from your PCL. 从您的PCL。 You can even subscribe to an event to see when connectivity changes: 您甚至可以订阅事件以查看连接性何时发生变化:

CrossConnectivity.Current.ConnectivityChanged += <handler>

This works on iOS and Android. 这适用于iOS和Android。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM