After some search with other resources and some common sense, the answer to get all mobile phones in the device is to query the ContactsContract.CommonDataKinds.Phone.CONTENT_URI instead of the ContactsContract.Data.CONTENT_URI and ran the cursor on that.
Android SDK - get contacts is very slow
-
21-06-2023 - |
문제
a new app, I need to import all contacts with mobile phone,
I runs the code below in an AsyncTask class.
Its works fine, but very slow, on a device with 2000 contacts, the device freeze for few moments. I know it can be done much faster since there are a lot of apps that use the contacts.
Any ideas?
public ArrayList<ContactInfo> getContacts() {
ArrayList<ContactInfo> arrayList = new ArrayList<ContactInfo>();
ContentResolver cr = GlobalData.instance().getContext().getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, Phone.DISPLAY_NAME + " ASC");
String id;
String name;
int counter = 0;
if (cur.getCount() > 0) {
int indexId= cur.getColumnIndex(ContactsContract.Contacts._ID);
int indexName = cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int indexHasPhoneNum = cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
Log.d("getContacts", "Start");
while (cur.moveToNext()) {
id = cur.getString(indexId);
name = cur.getString(indexName);
if (Integer.parseInt(cur.getString(indexHasPhoneNum)) > 0) {
// Query phone here. Covered next
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
while (phones.moveToNext()) {
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
if(type == Phone.TYPE_MOBILE){
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
arrayList.add(new ContactInfo(name, phoneNumber));
counter++;
}
}
phones.close();
}
}
Log.d("getContacts", "End (" + counter + ")" );
}
cur.close();
return arrayList;
해결책
제휴하지 않습니다 StackOverflow