【问题标题】:Xamarin Forms Check Internet ConnectivityXamarin 表单检查 Internet 连接
【发布时间】:2018-07-16 14:34:36
【问题描述】:

我正在尝试使用 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");
            }
        }
    }
}

【问题讨论】:

  • 您是否针对 PCL 和您的平台特定项目(Android、iOS)安装了 Connectivity 插件?该错误仅在您按下按钮时发生?
  • @BrunoCaceiro 在一个问题中,我读到您需要在需要时请求这些资源。检查这是否是您的原因。
  • 是的,@BrunoCaceiro 先生,我什至尝试在共享或 .net 类型中安装插件仍然是同样的错误
  • @AnirudhaGupta 有关如何解决这些问题的任何想法?
  • 你能发布完整的错误信息吗?以及它真正发生的地方。

标签: c# xaml xamarin xamarin.forms


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多