郭佳豪 6 months ago
parent 6dffe6a382
commit 77cf3e6975

@ -29,24 +29,47 @@ public class Contact {
private static HashMap<String, String> sContactCache; private static HashMap<String, String> sContactCache;
private static final String TAG = "Contact"; private static final String TAG = "Contact";
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER /**
* SQL
*
*
* 1.
* 2. MIME
* 3. RAW_CONTACT_IDphone_lookupmin_match'+'
*/
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN " + " AND " + Data.RAW_CONTACT_ID + " IN "
+ "(SELECT raw_contact_id " + "(SELECT raw_contact_id "
+ " FROM phone_lookup" + " FROM phone_lookup"
+ " WHERE min_match = '+')"; + " WHERE min_match = '+')";
/**
*
*
* 使
*
* @param context 访
* @param phoneNumber
* @return null
*/
public static String getContact(Context context, String phoneNumber) { public static String getContact(Context context, String phoneNumber) {
// 初始化联系人缓存
if(sContactCache == null) { if(sContactCache == null) {
sContactCache = new HashMap<String, String>(); sContactCache = new HashMap<String, String>();
} }
// 检查缓存中是否已存在该电话号码对应的联系人名称
if(sContactCache.containsKey(phoneNumber)) { if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber); return sContactCache.get(phoneNumber);
} }
// 构建查询条件,用于在联系人数据库中查找匹配的电话号码
String selection = CALLER_ID_SELECTION.replace("+", String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 查询联系人数据库,获取与电话号码对应的联系人名称
Cursor cursor = context.getContentResolver().query( Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI, Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME }, new String [] { Phone.DISPLAY_NAME },
@ -54,6 +77,7 @@ public class Contact {
new String[] { phoneNumber }, new String[] { phoneNumber },
null); null);
// 如果查询结果不为空,则获取联系人名称并缓存
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) {
try { try {
String name = cursor.getString(0); String name = cursor.getString(0);
@ -66,6 +90,7 @@ public class Contact {
cursor.close(); cursor.close();
} }
} else { } else {
// 如果未找到匹配的联系人记录日志并返回null
Log.d(TAG, "No contact matched with number:" + phoneNumber); Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null; return null;
} }

Loading…
Cancel
Save