我需要获取设备中所有联系人及其电话号码的明确列表。但是等等......我们知道某些联系人可能分配了多个号码,这完全取决于每个用户如何存储他的联系人。这是我做的:
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;
这个过程有效,但对于我的80个联系人,它需要1000-2000毫秒,我需要更快地工作:)
答案 0 :(得分:1)
Cursor contactPhones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + u.PhoneId,
null,
null);
这略微次优,因为您直接在查询中编码联系人ID字段,而不是将其作为参数。这意味着查询解析器每次都必须重新解析查询,而不是能够使用单个缓存副本。
提供ID作为参数:
Cursor contactPhones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " =? ",
new String[] { Integer.toString(u.PhoneId) },
null);
ContentResolver.query()
的{{3}}重申了这一指导:
使用问号参数标记,例如'phone =?'代替 选择参数中的显式值,以便查询 只有这些值不同才会被识别为缓存相同 目的。