/* * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.micode.notes.data; import android.content.Context; import android.database.Cursor; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Data; import android.telephony.PhoneNumberUtils; import android.util.Log; import java.util.HashMap; /** * Contact 类用于从联系人数据库中根据电话号码查找联系人名称。 * 使用缓存来优化查找性能,避免重复查询联系人数据库。 */ public class Contact { // 用于缓存电话号码到联系人名称的映射,减少重复查询 private static HashMap sContactCache; // 用于日志输出的 TAG 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 = '+')"; /** * 根据电话号码查找联系人名称。 * 使用缓存来提高性能,如果电话号码已经查询过,则直接从缓存中获取联系人名称。 * * @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); } // 使用 PhoneNumberUtils 将电话号码转换为适合匹配的格式 String selection = CALLER_ID_SELECTION.replace("+", PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); // 执行查询联系人数据库,获取联系人名称 Cursor cursor = context.getContentResolver().query( 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); // 返回联系人名称 return name; } catch (IndexOutOfBoundsException e) { // 如果出现查询结果格式错误,记录日志并返回 null Log.e(TAG, "Cursor get string error " + e.toString()); return null; } finally { // 确保查询完成后关闭 Cursor,避免内存泄漏 cursor.close(); } } else { // 如果没有匹配的联系人,记录日志并返回 null Log.d(TAG, "No contact matched with number:" + phoneNumber); return null; } } }