【发布时间】:2015-07-12 08:56:06
【问题描述】:
我一直在尝试优化我的代码以从 Android 联系人数据库中获取联系人详细信息。但无论我尝试什么,加载 80 个包含姓名、电话号码和联系人缩略图(位图)的联系人仍然需要大约 4-5 秒。
我在 AsyncTask 实例的 doInBackground() 内运行以下 sn-p:
Cursor cursor = null;
try {
String[] projection = {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.PHOTO_URI };
cursor = getBaseContext().getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, null, null, null);
int nameIdx = cursor.getColumnIndex(Phone.DISPLAY_NAME);
int phoneNumberIdx = cursor.getColumnIndex(Phone.NUMBER);
if(cursor.moveToFirst()) {
do {
String name = cursor.getString(nameIdx);
String phoneNumber = cursor.getString(phoneNumberIdx);
long contactId=getContactIDFromNumber(phoneNumber, getBaseContext());
Bitmap bmp=loadContactPhoto(getBaseContext().getContentResolver(), contactId);
item.add(new ContactObject(name, phoneNumber, null, null, bmp, contactId));
} while (cursor.moveToNext());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
以下是从电话号码中获取联系人ID并解码位图流的方法:
public static long getContactIDFromNumber(String contactNumber,Context context)
{
contactNumber = Uri.encode(contactNumber);
int phoneContactID = new Random().nextInt();
Cursor contactLookupCursor = context.getContentResolver().query(Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, contactNumber),new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID}, null, null, null);
while(contactLookupCursor.moveToNext()){
phoneContactID = contactLookupCursor.getInt(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup._ID));
}
contactLookupCursor.close();
return phoneContactID;
}
public Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
if (input == null) {
return BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.ic_launcher);
}
return BitmapFactory.decodeStream(input);
}
该程序运行良好,但我想知道,还有其他方法可以获取上述字段的联系方式吗?我知道,由于getContactIDFromNumber() 方法正在运行子查询以获取contactId,因此程序很慢。我正在使用它来检索联系人图像缩略图。谁能建议一个更好的方法来做到这一点?也许有一种方法可以完全消除这个子查询?
编辑:
long contactId = Long.parseLong(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
获取位图:
Uri contactPhotoUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
InputStream is=ContactsContract.Contacts.openContactPhotoInputStream(getBaseContext().getContentResolver(), contactPhotoUri);
Bitmap bitmap=null;
if(is!=null){
bitmap = BitmapFactory.decodeStream(is);
}
【问题讨论】:
标签: android bitmap android-sqlite android-contacts query-performance