在我的App.xaml.cs文件中,我正在使用CrossConnectivity插件检查主机连接性。 这是我的代码
CrossConnectivity.Current.ConnectivityChanged += async (sender, args) =>
{
if (!args.IsConnected)
DependencyService.Get<ISQLite>().ShowSnackBar("No Internet Connection");
if (args.IsConnected)
{
Task<bool> response = CrossConnectivity.Current.IsRemoteReachable("http://ws.****abc.com/", 5000);
bool res = await response;
if (!res)
{
await Current.MainPage.DisplayAlert("Message", "Service not available,Please contact to your system admin", "Ok");
}
}
};
通过主机连接很好,但是我得到了错误的响应。 该如何解决?
答案 0 :(得分:1)
您可以尝试将端口添加到IsRemoteReachable
方法中。所以代码就像这样
CrossConnectivity.Current.IsRemoteReachable("http://ws.****abc.com/", 80, 5000);
更详细的代码是:
public App()
{
InitializeComponent();
MainPage = new MainPage();
if (DoIHaveInternet())
{
Console.WriteLine("Great!!!!!!");
}
else {
Console.WriteLine("No!!!!!!");
}
CrossConnectivity.Current.ConnectivityChanged += async (sender, args) =>
{
if (!args.IsConnected)
Console.WriteLine("not connected!!!!!!!!");
//DependencyService.Get<ISQLite>().ShowSnackBar("No Internet Connection");
if (args.IsConnected)
{
Task<bool> response = CrossConnectivity.Current.IsRemoteReachable("https://m.baidu.com/", 80, 5000);
bool res = await response;
if (!res)
{
await Current.MainPage.DisplayAlert("Message", "Service not available,Please contact to your system admin", "Ok");
}
}
};
}
我使用Google Pixel电话调试此代码,捕获显示响应返回true:
注意:
1请确保您正确参照this
设置CrossConnectivity插件2为Android添加ACCESS_NETWORK_STATE和ACCESS_WIFI_STATE权限
3确保该URL对您的测试设备有用。您可以先在设备或模拟器的Chrome中打开它,然后进行检查。