此代码从联系人列表中获取联系人,姓名和照片,但是在获取所有这些内容时花费了太多时间。
所以我的问题是如果用户有超过500个联系人,那么它需要花费很多时间,以便如何减少其获取时间。
我在Stack Overflow上看过很多帖子但无法找到解决方案。
public void fetchContacts() {
list = new ArrayList<PersonDetails>();
String phoneNumber = null;
//Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
Uri CONTENT_URI= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
// StringBuffer output = new StringBuffer();
String[] PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER, };
String SELECTION = ContactsContract.Contacts.HAS_PHONE_NUMBER
+ "='1'";
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, PROJECTION,
SELECTION, null, null);
// Loop for every contact in the phone
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
//Log.e("i", i + "");
PersonDetails personDetails = null;
String contact_id = cursor.getString(cursor
.getColumnIndex(_ID));
String name = cursor.getString(cursor
.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor
.getString(cursor
.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
// Query and loop for every phone number of the
// contact
String Phone_Projection[] = new String[] { Phone.NUMBER };
Cursor phoneCursor = contentResolver.query(
PhoneCONTENT_URI, Phone_Projection,
Phone_CONTACT_ID + " = ?",
new String[] { contact_id }, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor
.getColumnIndex(NUMBER));
// output.append("\n Phone number:" +
// phoneNumber);
}
phoneCursor.close();
if (phoneNumber != null
&& phoneNumber.length() >= 10) {
Uri ur = null;
try {
Uri person = ContentUris
.withAppendedId(
ContactsContract.Contacts.CONTENT_URI,
Long.parseLong(contact_id));
ur = Uri.withAppendedPath(
person,
ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
personDetails = new PersonDetails();
if (name != null) {
personDetails.setName(name);
}
if (phoneNumber != null) {
//Log.e("Phone", phoneNumber);
personDetails.setSocialId(phoneNumber);
}
if (ur != null) {
//Log.e("URI", ur.toString());
personDetails.setPhotoUrl(ur.toString());
}
personDetails.setSocialFlag(5);
}
}
if (personDetails != null) {
list.add(personDetails);
}
}
}
try {
if (cursor != null) {
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}