我需要在程序中读取联系人列表,是不是要用android.provider.ContactsContract?我不知道应该怎么去用它,找不到合适的例子。谁能告诉我哪能找到啊?能在这里直接告诉我实现的方法那是更好了:)

推荐图书

  • Android 2高级编程(第2版)
  • Google Android SDK开发范例大全(第2版)
  • 疯狂Android讲义


1个回答

首先在AndroidManifest.xml文件中加上android.permission.READ_CONTACTS,然后你可以用下面的代码来实现:

Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null); 
while (cursor.moveToNext()) { 
   String contactId = cursor.getString(cursor.getColumnIndex( 
   ContactsContract.Contacts._ID)); 
   String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); 
   if (Boolean.parseBoolean(hasPhone)) { 
      // You know it has a number so now query it like this
      Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null); 
      while (phones.moveToNext()) { 
         String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));                 
      } 
   phones.close(); 
}

Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null); 
while (emails.moveToNext()) { 
   // This would allow you get several email addresses 
   String emailAddress = emails.getString( 
   emails.getColumnIndex(ContactsContract.CommonDataKinds.CommonDataColumns.DATA)); 
} 
emails.close(); 
cursor.close(); 

如果你只想获取联系人中的名字和电话号码,可以这样:

Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

while(people.moveToNext()) {
   int nameFieldColumnIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
   String contact = people.getString(nameFieldColumnIndex);
   int numberFieldColumnIndex = people.getColumnIndex(PhoneLookup.NUMBER);
   String number = people.getString(numberFieldColumnIndex);
}

people.close();