From f869bbe3080b9bbdea1b2913f54da36d46ce53ef Mon Sep 17 00:00:00 2001 From: xz <3132942900@qq.com> Date: Thu, 21 Dec 2023 14:11:09 +0800 Subject: [PATCH] Update Contact.java --- .../java/net/micode/notes/data/Contact.java | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/net/micode/notes/data/Contact.java b/app/src/main/java/net/micode/notes/data/Contact.java index d97ac5d..8c8ff91 100644 --- a/app/src/main/java/net/micode/notes/data/Contact.java +++ b/app/src/main/java/net/micode/notes/data/Contact.java @@ -26,47 +26,48 @@ import android.util.Log; import java.util.HashMap; public class Contact { - private static HashMap sContactCache; - private static final String TAG = "Contact"; + private static HashMap 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 " + "(SELECT raw_contact_id " + " FROM phone_lookup" + " WHERE min_match = '+')"; - + // 根据电话号码获取联系人 public static String getContact(Context context, String phoneNumber) { if(sContactCache == null) { - sContactCache = new HashMap(); + sContactCache = new HashMap();// 如果缓存为空,则创建一个新的哈希映射表 } - if(sContactCache.containsKey(phoneNumber)) { + if(sContactCache.containsKey(phoneNumber)) {// 如果缓存中已存在该电话号码的联系人信息,则直接返回 return sContactCache.get(phoneNumber); } String selection = CALLER_ID_SELECTION.replace("+", - PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); + PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));// 根据电话号码生成查询条件语句 Cursor cursor = context.getContentResolver().query( Data.CONTENT_URI, new String [] { Phone.DISPLAY_NAME }, selection, new String[] { phoneNumber }, - null); + null);// 执行查询操作,获取联系人的姓名 - if (cursor != null && cursor.moveToFirst()) { + if (cursor != null && cursor.moveToFirst()) {// 如果查询结果非空且有数据 try { - String name = cursor.getString(0); - sContactCache.put(phoneNumber, name); - return name; + String name = cursor.getString(0);// 获取联系人姓名 + sContactCache.put(phoneNumber, name);// 将联系人信息添加到缓存中 + return name;// 返回联系人姓名 } catch (IndexOutOfBoundsException e) { - Log.e(TAG, " Cursor get string error " + e.toString()); + 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); + Log.d(TAG, "No contact matched with number:" + phoneNumber);// 输出未找到匹配联系人的日志信息 return null; } }