0
在我的Android應用程序中,活動是顯示用戶手機中的聯繫人列表。 問題是,該操作需要大約3秒鐘執行,不用說這是完全不可接受的。 這裏是我使用的代碼:如何在聯繫人上查詢聯繫人Android
private List<Contact> retrieveContacts(ContentResolver contentResolver) {
LinkedHashSet<Contact> contactSet = new LinkedHashSet<Contact>();
List<Contact> listContacts = new ArrayList<Contact>();
final Cursor cursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER }, null,
null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor == null);
if (cursor.moveToFirst() == true) {
do {
final String name = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
final String telephone = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Contact contact = new Contact(telephone, name, false, false);
contactSet.add(contact);
} while (cursor.moveToNext() == true);
}
if (cursor.isClosed() == false) {
cursor.close();
}
for (Contact contact : contactSet){
listContacts.add(contact);
}
return listContacts;
}
我然後填充retrieveContacts的結果一個ListView。 我正在使用LinkedHashSet,因爲它不接受重複,並且它保持用於添加元素的順序。 (我需要保留那個訂單)
這樣的查詢需要花費那麼多時間嗎?有什麼辦法可以改善它的表現嗎?
「多少時間」?你有多少聯繫人,以及「多少時間」是多少? – pskink
我在我的問題中提到了3秒鐘。在我的情況下,大約有一百個聯繫人,我認爲它不是那麼大。 – Kritias
嗯,它應該採取<** 100毫秒**(** 0.1 **秒),而不是** 3 **秒,而不是** 1 **秒,請參閱我的答案在這裏:http://stackoverflow.com/a/26820544/2252830,它不僅可以獲取姓名和電話號碼,還可以獲得電子郵件帳號 – pskink