/* * 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. * 总体分析 这段 Java 代码定义了Contact类,主要用于实现根据电话号码获取对应联系人姓名的功能。它通过维护一个静态的HashMap作为缓存(sContactCache)来避免重复查询,利用安卓系统的ContentResolver结合特定的查询条件(CALLER_ID_SELECTION)从联系人数据提供者(Data.CONTENT_URI)中查找匹配电话号码的联系人姓名信息,若找到则存入缓存并返回,整体旨在提高获取联系人姓名操作的效率,优化在应用中频繁查询联系人相关信息的性能。 函数分析 getContact方法 所属类:Contact 功能:首先判断缓存HashMap(sContactCache)是否为null,若是则创建一个新的实例。接着检查传入的电话号码是否已存在于缓存中,若存在则直接从缓存获取并返回对应的联系人姓名。若不在缓存中,会先替换查询条件(CALLER_ID_SELECTION)中的占位符,将电话号码转换为适合查询的格式,然后通过ContentResolver发起查询,若游标不为null且能移动到第一条记录,则尝试获取联系人姓名,存入缓存后返回该姓名;若游标为null或者获取过程出现异常(捕获IndexOutOfBoundsException)则记录相应日志并返回null,用于根据给定的电话号码查找并返回对应的联系人姓名,同时利用缓存机制减少重复查询开销。 */ 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; public class 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(); } 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); 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; } } }