2016-11-25 119 views
0

我想要获取与Xamarin.Android联系的所有电话号码和电子邮件。我发现这https://stackoverflow.com/a/2356760/4965222,但我不能应用这个原始的android配方Xamarin.Android,因为没有找到我可以得到Phones._ID,Phones.TYPE,Phones.NUMBER, Phones.LABEL, People.Phones.CONTENT_DIRECTORY。如何在没有Xamarin.Mobile库的情况下获取这些数据?获取联系人的所有电话号码Xamarin.Android

+2

“我不能应用这个原始的android食谱” - 为什么不呢?这是一小段代码 - 所有必需的API应该在Xamarin中可用。也许如果你告诉我们,当你试图将这段代码转换为C#时,你会遇到什么具体问题,我们可以更好地帮助你。 – Jason

+0

@jason对不起,我不清楚。也许现在这更好地描述问题 –

+0

https://developer.xamarin.com/api/type/Android.Provider.Contacts+People+Phones/ – Jason

回答

1

文献研究后,我找到了答案。

//filtering phones related to a contact 
    var phones = Application.Context.ContentResolver.Query(
     ContactsContract.CommonDataKinds.Phone.ContentUri, 
     null, 
     ContactsContract.CommonDataKinds.Phone.InterfaceConsts.ContactId 
     + " = " + contactId, null, null); 
    // getting phone numbers 
    while (phones.MoveToNext()) 
    { 
     var number = 
      phones.GetString(   //specify which column we want to get 
       phones.GetColumnIndex(ContactsContract.CommonDataKinds.Phone.Number)); 
     // do work with number 
    } 
    phones.Close(); 
1

这里是起点

public List<PersonContact> GetPhoneContacts() 
    { 
     var phoneContacts = new List<PersonContact>(); 

     using (var phones = ApplicationContext.ContentResolver.Query(ContactsContract.CommonDataKinds.Phone.ContentUri, null, null, null, null)) 
     { 
      if (phones != null) 
      { 
       while (phones.MoveToNext()) 
       { 
        try 
        { 
         string name = phones.GetString(phones.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.DisplayName)); 
         string phoneNumber = phones.GetString(phones.GetColumnIndex(ContactsContract.CommonDataKinds.Phone.Number)); 

         string[] words = name.Split(' '); 
         PersonContact contact = new PersonContact(); 
         contact.FirstName = words[0]; 
         if (words.Length > 1) 
          contact.LastName = words[1]; 
         else 
          contact.LastName = ""; //no last name, is that ok? 
         contact.PhoneNumber = phoneNumber; 
         phoneContacts.Add(contact); 
        } 
        catch (Exception ex) 
        { 
         //something wrong with one contact, may be display name is completely empty, decide what to do 
        } 
       } 
       phones.Close(); //not really neccessary, we have "using" above 
      } 
      //else we cannot get to phones, decide what to do 
     } 

     return phoneContacts; 
    } 


public class PersonContact 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string PhoneNumber { get; set; } 
} 
相关问题