在Android上使用"手机号码"查询联系人的最快方式

and*_*per 7 performance android contacts

我需要从设备及其电话号码中获取所有联系人的明确列表.但是等等......我们知道某些联系人可能分配了多个号码,这完全取决于每个用户如何存储他的联系人.这是我做的:

    ContentResolver cr = context.getContentResolver();   
    Uri uri = ContactsContract.Contacts.CONTENT_URI;
    String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME };
    String selection =  ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1'";
    String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
    ArrayList<user> contacts = new ArrayList<user>();

    Cursor users = a.managedQuery(uri, projection, selection, null, sortOrder);

    while (users.moveToNext()) {
        user u = new user();
        u.PhoneId = users.getInt(users.getColumnIndex(ContactsContract.Contacts._ID));
        u.Name = users.getString(users.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

        String homePhone = "", cellPhone = "", workPhone = "", otherPhone = "";
        Cursor contactPhones = cr.query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + " = " + u.PhoneId, null, null);

        while (contactPhones.moveToNext()) {

            String number = contactPhones.getString(contactPhones.getColumnIndex(Phone.NUMBER));
            int type = contactPhones.getInt(contactPhones.getColumnIndex(Phone.TYPE));
            switch (type) {
                case Phone.TYPE_HOME:   homePhone = number; break;
                case Phone.TYPE_MOBILE:  cellPhone = number; break;
                case Phone.TYPE_WORK:   workPhone = number; break;
                case Phone.TYPE_OTHER:  otherPhone = number; break;
                }
        }        
        u.Phone = ((cellPhone!="") ? cellPhone : ((homePhone!="") ? homePhone : ((workPhone!="") ? workPhone : otherPhone)));
    }

    return contacts;
Run Code Online (Sandbox Code Playgroud)

这个过程有效但是我的80个联系人需要1000-2000毫秒,我需要更快地工作:)

Gra*_*and 1

Cursor contactPhones = cr.query(Phone.CONTENT_URI, null, 
                                Phone.CONTACT_ID + " = " + u.PhoneId, 
                                null, 
                                null);
Run Code Online (Sandbox Code Playgroud)

这有点次优,因为您直接在查询中对联系人 ID 字段进行编码,而不是将其作为参数。这意味着查询解析器每次都必须重新解析查询,而不是能够使用单个缓存副本。

请提供 ID 作为参数:

Cursor contactPhones = cr.query(Phone.CONTENT_URI, null, 
                                Phone.CONTACT_ID + " =? ", 
                                new String[] { Integer.toString(u.PhoneId) }, 
                                null);
Run Code Online (Sandbox Code Playgroud)

javadoc重申了这一指导ContentResolver.query()

使用问号参数标记,例如“phone=?” 而不是选择参数中的显式值,以便仅这些值不同的查询将被识别为相同的查询以用于缓存目的。