diff --git a/src/小米标签代码/src/net/micode/notes/data/Contact.java b/src/小米标签代码/src/net/micode/notes/data/Contact.java index d97ac5d..d151e8d 100644 --- a/src/小米标签代码/src/net/micode/notes/data/Contact.java +++ b/src/小米标签代码/src/net/micode/notes/data/Contact.java @@ -25,10 +25,21 @@ import android.util.Log; import java.util.HashMap; +/** + * 联系人工具类 + * 用于根据电话号码获取联系人姓名 + */ public class Contact { + // 联系人缓存,用于提高性能,避免重复查询 private static HashMap 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(); } + // 首先检查缓存中是否有该电话号码对应的联系人 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; } } -} +} \ No newline at end of file