我正在开发一个SMS应用程序,遇到了以下问题。目前,我可以使用提供程序Telephony.Sms.Conversations
通过使用CursorLoader
来阅读SMS对话。从这个CursorLoader
返回的光标中,我可以显示对话的地址,这些地址是电话号码。
我的问题是如何有效地检索SMS对话联系人姓名以与SMS对话一起显示,而不是电话号码。无论如何可以从之前CursorLoader
返回的电话号码列表中加载联系人列表?当然,我尝试使用电话号码逐个加载联系人姓名,但这会大大降低应用程序性能。
提前谢谢你。
我一直在寻找解决方案,最终提出了一个很好的折衷方案。
查询完成后,我将我的值存储在HashMap<String, String> contact_map
int SENDER_ADDRESS = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.ADDRESS);
while (cursor.moveToNext()) {
contact_map.put(
cursor.getString(SENDER_ADDRESS),
getContactName(getApplicationContext(), cursor.getString(SENDER_ADDRESS))
);
}
方法获取联系人姓名:
public static String getContactName(Context context, String phoneNumber) {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor == null) {
return null;
}
String contactName = null;
if(cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
if(cursor != null && !cursor.isClosed()) {
cursor.close();
}
if (contactName != null) {
return contactName;
} else {
return phoneNumber;
}
}
编辑:然后我得到联系人姓名
String name = contact_map.get(cursor.getString(SENDER_ADDRESS));
希望对您有所帮助!