2024/11/30 对contact包改进缓存机制并加注解

dcy
dcy 1 year ago
parent a937d06db9
commit 2a7bc321fc

@ -24,50 +24,76 @@ import android.telephony.PhoneNumberUtils;
import android.util.Log;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class Contact { //联系人
private static HashMap<String, String> sContactCache;
// 定义最大缓存数量可根据实际情况调整这里假设最多缓存100个联系人信息
private static final int MAX_CACHE_SIZE = 100;
// 使用LinkedHashMap来实现缓存它能保持插入顺序方便后续按顺序清理较旧的缓存项
private static LinkedHashMap<String, String> sContactCache;
private static final String TAG = "Contact";
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 Android访
* @param phoneNumber
* @return null
*/
public static String getContact(Context context, String phoneNumber) {
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
// 初始化缓存如果缓存还未创建则创建一个新的LinkedHashMap实例
if (sContactCache == null) {
sContactCache = new LinkedHashMap<String, String>() {
// 重写removeEldestEntry方法用于定义在何种情况下移除最老的缓存项
@Override
protected boolean removeEldestEntry(Map.Entry<String, String> eldest) {
// 当缓存的数量大于等于最大缓存数量时返回true表示需要移除最老的缓存项
return size() >= MAX_CACHE_SIZE;
}
};
}
if(sContactCache.containsKey(phoneNumber)) {
// 先检查缓存中是否已经存在该电话号码对应的联系人姓名
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 },
new String[]{Phone.DISPLAY_NAME},
selection,
new String[] { phoneNumber },
new String[]{phoneNumber},
null);
if (cursor != null && cursor.moveToFirst()) {
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 {
// 如果没有查询到对应的联系人,记录一条调试日志
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}
}
}
}
Loading…
Cancel
Save