1

目前我正在使用Xamarin.Essentials.Connectivity来检查我的互联网连接。我正在使用下面的代码在进行交易之前检查是否有互联网。如何检查我的表单中的 Internet 连接是否发生变化?例如,我有两 (2) 个表单登录表单主菜单,无论我当前处于何种表单,当我打开设备的 Wifi 时,它都会显示一条警报,提示我没有互联网连接。我怎样才能做到这一点?

var current = Connectivity.NetworkAccess;

//Check if there is an internet connection
if (current == NetworkAccess.Internet)
{
   DisplayAlert("Ok", "Connected", "Ok");
}
else {
   DisplayAlert("Error", Connected, "Ok");
}

我尝试使用 Xamarin.Essentials.Connectivity 文档中的此代码,但我不知道如何使用它以及将其放在哪里

public class ConnectivityTest
{
   public ConnectivityTest()
   {
       // Register for connectivity changes, be sure to unsubscribe when finished
       Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
   }

   void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs  e)
   {
       var access = e.NetworkAccess;
       var profiles = e.Profiles;
   }
}

我的同步代码

public async void FirstSyncUser(string host, string database, string contact)
    {
        try
        {
            var db = DependencyService.Get<ISQLiteDB>();
            var conn = db.GetConnection();

            var sql = "SELECT * FROM tblUser WHERE ContactID = '" + contact + "'";
            var getUser = conn.QueryAsync<UserTable>(sql);
            var resultCount = getUser.Result.Count;

            //Check if the user has been sync
            if (resultCount < 1)
            {
                try
                {
                    syncStatus.Text = "Syncing User Data";

                    var link = Constants.requestUrl + "Host=" + host + "&Database=" + database + "&Contact=" + contact + "&Request=8qApc8";
                    string contentType = "application/json";
                    JObject json = new JObject
                    {
                        { "ContactID", contact }
                    };

                    HttpClient client = new HttpClient();
                    var response = await client.PostAsync(link, new StringContent(json.ToString(), Encoding.UTF8, contentType));

                    if (response.IsSuccessStatusCode)
                    {
                        var content = await response.Content.ReadAsStringAsync();

                        if(content != "")
                        {
                            var userresult = JsonConvert.DeserializeObject<List<UserData>>(content);
                            for (int i = 0; i < userresult.Count; i++)
                            {
                                syncStatus.Text = "Syncing User Data " + (i + 1) + " out of " + userresult.Count;

                                var item = userresult[i];
                                var contactID = item.ContactID;
                                var userID = item.UserID;
                                var userPassword = item.UserPassword;
                                var userType = item.UserType;
                                var userStatus = item.UserStatus;
                                var lastSync = Convert.ToDateTime(item.LastSync);
                                var serverUpdate = Convert.ToDateTime(item.ServerUpdate);
                                var mobileUpdate = Convert.ToDateTime(item.MobileUpdate);

                                var user = new UserTable
                                {
                                    ContactID = Convert.ToInt32(contactID),
                                    UserID = userID,
                                    UserPassword = userPassword,
                                    UserType = userType,
                                    UserStatus = userStatus,
                                    LastSync = lastSync,
                                    ServerUpdate = serverUpdate,
                                    MobileUpdate = mobileUpdate
                                };

                                await conn.InsertAsync(user);
                            }
                        }
                        else
                        {
                            //Proceed to next function
                            FirstSyncContacts(host, database, contact);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.Write("Syncing User Error " + ex.Message);
                }

                //Proceed to next function
                FirstSyncContacts(host, database, contact);
            }
            //If not get the user
            else
            {
                SyncUser(host, database, contact);
            }
        }
        catch (Exception ex)
        {
            Console.Write("Syncing User Error " + ex.Message);
        }
    }
4

1 回答 1

1

你能告诉我如何以及在哪里放这个吗?为了在全球范围内使用它

这是通过 OnStart、OnSleep 和 OnResume 覆盖在表单的应用程序级别使用 Essentials.Connectivity 的示例

public partial class App : Application
{
    ~~~~

    protected override void OnStart()
    {
        Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
    }

    protected override void OnSleep()
    {
        Connectivity.ConnectivityChanged -= Connectivity_ConnectivityChanged;
    }

    protected override void OnResume()
    {
        Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
    }

    void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
    {
        Page page;
        if (MainPage is NavigationPage)
        {
            page = ((NavigationPage)MainPage).CurrentPage;
        }
        else
        {
            page = MainPage;
        }
        page.DisplayAlert("Status", e.NetworkAccess.ToString(), "OK");
    }

}
于 2018-10-03T01:16:08.513 回答