Xamarin表格检查Internet连接

时间:2018-07-16 14:34:36

标签: c# xaml xamarin xamarin.forms

我正在尝试使用Xamarin检查互联网连接。我目前正在遵循 https://www.youtube.com/watch?v=xVXVs_CHxAU&t=132s 的教程。

我收到错误“调用目标抛出异常” 。是什么原因造成的?以及如何解决?

我使用 Xam.Plugin.Connectivity v3.2.0 作为记录,我尝试使用此nuget软件包的较旧版本时,仍然发生相同的错误。我在调试中使用Xamarin Live。我已经将 ACCESS_WIFI_STATE,ACCESS_NETWORK_STATE,INTERNET 添加到了我的android清单中。

XAML代码:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:TBSApplication"
             x:Class="TBSApplication.MainPage">
    <ContentPage.Content>
        <ScrollView>
            <StackLayout>
                <Button x:Name="Btn" Text="Check Connectivity" Clicked="Btn_Clicked"/>
                <Label x:Name="Lbl" Text="Status"/>
                <Label x:Name="Lbl1" Text="Type:"/>
            </StackLayout>
        </ScrollView>
    </ContentPage.Content>
</ContentPage>



XAML.cs代码:

using Plugin.Connectivity;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace TBSApplication
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void Btn_Clicked(object sender, EventArgs e)
        {
            try
            {
                var isConnected = CrossConnectivity.Current.IsConnected;

                if (isConnected == true)
                {
                    DisplayAlert("Message", "Connected", "Ok");
                }
                else
                {
                    DisplayAlert("Message", "Not Connected", "Ok");
                }
            }
            catch (System.Exception ex)
            {
                DisplayAlert("Message", ex.Message, "Ok");
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

请勿使用Xamarin Live Player测试您的应用。 Xamarin Live Player非常适合测试设计导航,但就功能而言,它运作不佳。启用开发人员模式,尝试使用模拟器或移动设备本身。