2016-11-25 111 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; } 
} 
相關問題