我需要从设备及其电话号码中获取所有联系人的不同列表。但是等等...我们知道某些联系人可能分配了多个号码,这完全取决于每个用户如何存储他的联系人。这是我所做的:
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 毫秒,我需要更快地工作:)
最佳答案
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);
javadoc ContentResolver.query()
重申了这一指导方针:
Use question mark parameter markers such as 'phone=?' instead of explicit values in the selection parameter, so that queries that differ only by those values will be recognized as the same for caching purposes.
关于android - 在 Android 上使用 "mobile phone numbers"查询联系人的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6066009/