data/Contact.java

hsy_branch
何思源 3 months ago
parent 59dbe07a37
commit d5cba8d474

@ -25,28 +25,59 @@ import android.util.Log;
import java.util.HashMap;
/**
*
*
*/
public class Contact {
/**
*
*
*
*/
private static HashMap<String, String> sContactCache;
/**
*
*/
private static final String TAG = "Contact";
/**
* SQL
*
* 使PHONE_NUMBERS_EQUAL
* MIMEPhone.CONTENT_ITEM_TYPE
* 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.RAW_CONTACT_ID + " IN "
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
+ "(SELECT raw_contact_id "
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
/**
*
* @param context
* @param phoneNumber
* @return null
*/
public static String getContact(Context context, String phoneNumber) {
// 初始化缓存
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
// 如果缓存中已存在该电话号码对应的联系人名称,则直接返回
if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber);
}
// 构建查询条件,将电话号码转换为最小匹配格式
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 查询联系人信息
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME },
@ -54,18 +85,24 @@ public class Contact {
new String[] { phoneNumber },
null);
// 处理查询结果
if (cursor != null && cursor.moveToFirst()) {
try {
// 获取联系人名称
String name = cursor.getString(0);
// 将结果缓存
sContactCache.put(phoneNumber, name);
return name;
} catch (IndexOutOfBoundsException e) {
// 捕获索引越界异常并记录日志
Log.e(TAG, " Cursor get string error " + e.toString());
return null;
} finally {
// 关闭游标
cursor.close();
}
} else {
// 如果未找到匹配的联系人记录日志并返回null
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}

Loading…
Cancel
Save