这个类是在别人的方法基础上修改的.
class GetContacts implements Runnable {
@Override
public void run() {
try {
// TODO Auto-generated method stub
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.PHOTO_ID };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cursor = managedQuery(uri, projection, selection, selectionArgs, sortOrder);
Cursor phonecur = null;
while (cursor.moveToNext()) {
// 取得联系人名字
int nameFieldColumnIndex = cursor.getColumnIndex(android.provider.ContactsContract.PhoneLookup.DISPLAY_NAME);
String name = cursor.getString(nameFieldColumnIndex);
// 取得联系人ID
String contactId = cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts._ID));
phonecur = managedQuery(android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, android.provider.ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
+ contactId, null, null);
// 取得电话号码(可能存在多个号码)
while (phonecur.moveToNext()) {
String strPhoneNumber = phonecur.getString(phonecur.getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER));
if (strPhoneNumber.length() > 4)
mList.add(new Contact(name, strPhoneNumber));
}
}
if (phonecur != null)
phonecur.close();
cursor.close();
// 更新数据
runOnUiThread(new Runnable() {
@Override
public void run() {
listview.setAdapter(adapter);
hideMessage();
}
});
} catch (Exception e) {
YxUtil.showToast(context, "权限获取失败");
}
}
}
上面的Contact类是我自己写的一个javabean用于封装联系人数据:
public class Contact {
public Contact(String name, String phone) {
this.name = name;
this.phone = phone;
}
public String name;
public String phone;
public boolean check = false;
}
另外, 还需要读取联系人的权限:
<uses-permission android:name="android.permission.READ_CONTACTS" />