我正在尝试使用他们的姓名,电子邮件和电话号码查询设备上的所有联系人列表。
一切都运作良好。但是,获取所有数据大约需要5-8秒(大约1000个联系人)。
据我了解,获取电话号码和电子邮件,每个都需要一个单独的查询,这可能是整个操作花了这么长时间的原因。
有没有办法在一个查询请求中查询姓名,号码和电子邮件?
public class MainActivity extends AppCompatActivity {
private static final String[] PROJECTION =
{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.LOOKUP_KEY,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Contact> contacts = new ArrayList<Contact>();
ContentResolver contentResolver = getContentResolver();
Cursor contactsCursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, null, null, null);
if (contactsCursor == null)
return;
while (contactsCursor.moveToNext()) {
String id = contactsCursor.getString(contactsCursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = contactsCursor.getString(contactsCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));
ArrayList<String> numbers = getPhoneNumbers(id, contentResolver);
ArrayList<String> emails = getEmailAddress(id, contentResolver);
contacts.add(new Contact(name, emails, numbers, id));
}
Log.d("", "" +contacts.size());
contactsCursor.close();
}
private ArrayList<String> getPhoneNumbers(String id, ContentResolver contentResolver) {
ArrayList<String> phoneNumbers = new ArrayList<>();
Cursor cursorPhone = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{id},
null);
if (cursorPhone == null)
return phoneNumbers;
if (cursorPhone.moveToFirst()) {
phoneNumbers.add(cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
cursorPhone.close();
return phoneNumbers;
}
private ArrayList<String> getEmailAddress(String id, ContentResolver contentResolver){
ArrayList<String> emails = new ArrayList<>();
Cursor cursorEmail = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
if(cursorEmail == null)
return emails;
while (cursorEmail.moveToNext()){
emails.add(cursorEmail.getString(cursorEmail.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
}
cursorEmail.close();
return emails;
}
}