Xamarin Forms:如何在将号码添加到 phone 簿后获取 phone 的最新联系人?

Xamarin Forms: How to fetch the latest contacts of phone after adding a number to phonebook?

我已经提到了 this blog for listing the phone contacts. Also, I have implemented adding contacts to the phonebook using DependencyService as per this 话题。

我的问题是在向设备添加联系人后 phone 我需要获取所有最新的联系人。另外,我需要在联系人列表视图中显示新联系人。

为了参考,我创建了一个示例项目并上传了它 here。在此示例中,我首先 列出了 phone 联系人 ,并在顶部添加了 添加新联系人 选项。如果我们点击 添加新,将打开一个新页面,其中包含 添加到联系人 选项和 phone 号码条目。输入 phone 号码后单击 添加到联系人 选项,然后设备 phone 书页将显示输入的 phone 号码。

在此阶段,用户可能会也可能不会将该号码保存到设备 phonebook。因此,当用户恢复到应用程序时,我需要获取整个联系人并检查 phone 号码是否已添加到设备 phone 簿中。如果添加了联系人,我将隐藏 添加到联系人 选项,否则我将再次显示该选项。同时当用户返回联系人列表时,我需要在那边显示新添加的联系人。

为此,我在 App.xaml.cs 上添加了一条消息,并在 AddContactPage.

上订阅了它

App.xaml.cs

protected override void OnResume()
{
    // Handle when your app resumes
    MessagingCenter.Send(this, "isContactAdded");
}

AddContactPage

MessagingCenter.Subscribe<App>(this, "isContactAdded", (sender) =>
{
    //How I can fetch the entire latest contacts here
    //After fetching conatcts only I can check the new phone number is added to the device phonebook
});

联系人作为参数从 MainActivity 传递到 App.xaml.cs。所以我不知道如何直接获取它。有没有办法获取此页面上的所有联系人?

//loading all the new contacts
protected async override void OnResume()
{
    if (Utility.isContactAdding)
    {
        UserDialogs.Instance.ShowLoading("");
        List<Contact> contacts = await contactsService.RetrieveContactsAsync() as List<Contact>;
        MessagingCenter.Send<App, List<Contact>>(App.Current as App, "isContactAdded", contacts);
    }
}

//Comparing the new contacts with phone number
MessagingCenter.Subscribe<App, List<Contact>>(App.Current, "isContactAdded", (snd, arg) =>
{
    Device.BeginInvokeOnMainThread(() =>
    {
        Utility.ContactsList.Clear();
        phone = Regex.Replace(phone, @"[^0-9+]+", "");
        bool isContactExist = false;
        var AllNewContacts = arg as List<Contact>;
        foreach(var item in AllNewContacts)
        {
            if (item.PhoneNumbers.Length != 0)
            {
                foreach(var number in item.PhoneNumbers)
                {
                    if (number.Replace("-", "").Replace(" ","") == phone)
                    {
                        isContactExist = true;
                    }
                }
            }
            Utility.ContactsList.Add(item);
        }
        if (isContactExist)
        {
            Phonebook_layout.IsVisible = false;
            MessagingCenter.Send<CallHistoryDetailPage>(this, "refreshcontacts");
        }
        else
        {
            Phonebook_layout.IsVisible = true;
        }
        Utility.isContactAdding = false;
        UserDialogs.Instance.HideLoading();
    });
});

//Subscribed message and refershing the contacts
MessagingCenter.Subscribe<CallHistoryDetailPage>(this, "refreshcontacts", (sender) =>
{
    BindingContext = new ContactsViewModel(Utility.myContacts);
});