zhangqing 4 months ago
parent f4a1eb2f2b
commit 1b7764a848

@ -25,10 +25,21 @@ import android.util.Log;
import java.util.HashMap;
/**
*
*
*/
public class Contact {
// 联系人缓存,用于提高性能,避免重复查询
private static HashMap<String, String> sContactCache;
// 日志标签
private static final String TAG = "Contact";
/**
* SQL
*
*/
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 "
@ -36,38 +47,54 @@ public class Contact {
+ " 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 },
selection,
new String[] { phoneNumber },
null);
Data.CONTENT_URI, // 联系人数据URI
new String [] { Phone.DISPLAY_NAME }, // 要查询的列:显示名称
selection, // 选择条件
new String[] { phoneNumber }, // 选择参数:电话号码
null); // 排序方式
// 处理查询结果
if (cursor != null && cursor.moveToFirst()) {
try {
String name = cursor.getString(0);
sContactCache.put(phoneNumber, name);
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();
cursor.close(); // 确保关闭游标
}
} else {
// 没有找到匹配的联系人
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}
}
}
}
Loading…
Cancel
Save