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

问题描述

我已参考 this 博客列出电话联系人。此外,我已经按照 this 线程使用 DependencyService 实现了向电话簿添加联系人。

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

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

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

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

App.xaml.cs

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

添加联系人页面

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,(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);
});