加载所有联系人和所有电话号码的有效方式(Android 2.0)

时间:2011-08-23 13:18:43

标签: android contacts

有没有办法获取所有联系人的所有电话号码,而无需为每个联系人单独查询? (使用Android 2.0+)。如果你有超过100个联系人(在低端手机上无法使用),它真的很慢,我想知道我是否可以做更有效的查询。

目前我正在获取一个包含所有有效ContactsContract.Contacts.IN_VISIBLE_GROUP联系人的游标,然后为每个联系人单独查询以获取所有数字。

获取联系人的片段只是提交名称和查找键:

Uri uri = ContactsContract.Contacts.CONTENT_URI;

String[] projection = new String[] {
    ContactsContract.Contacts.DISPLAY_NAME,
    ContactsContract.Contacts.LOOKUP_KEY};

然后每个联系人使用查找键。

Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
Uri res = ContactsContract.Contacts.lookupContact(contentResolver, lookupUri);

String[] projection =  new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER};

...

Cursor phones = contentResolver.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, phoneProjection, selection, selectionArgs, sortOrder);   

1 个答案:

答案 0 :(得分:16)

检查以下代码是否有帮助

    public ArrayList<PhoneContactInfo> getAllPhoneContacts() {
    Log.d("START","Getting all Contacts");
    ArrayList<PhoneContactInfo> arrContacts = new ArrayList<PhoneContactInfo>();
    PhoneContactInfo phoneContactInfo=null;     
    Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    Cursor cursor = context.getContentResolver().query(uri, new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone._ID}, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    cursor.moveToFirst();
    while (cursor.isAfterLast() == false)
    {
        String contactNumber= cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));  
        String contactName =  cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        int phoneContactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));


        phoneContactInfo = new PhoneContactInfo();
        phoneContactInfo.setPhoneContactID(phoneContactID);             
        phoneContactInfo.setContactName(contactName);                   
        phoneContactInfo.setContactNumber(contactNumber); 
        if (phoneContactInfo != null)
        {
            arrContacts.add(phoneContactInfo);
        }
        phoneContactInfo = null; 
        cursor.moveToNext();
    }       
    cursor.close();
    cursor = null;
    Log.d("END","Got all Contacts");
    return arrContacts;
}