/* * 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; //声明该类属于net.micode.notes.data包 import android.content.Context; //导入Context类,用于获取应用的上下文 import android.database.Cursor; //导入Cursor类,用于处理数据库查询的结果 import android.provider.ContactsContract.CommonDataKinds.Phone; //导入Phone类,访问联系人相关信息 import android.provider.ContactsContract.Data; //导入Data类,用于访问数据表 import android.telephony.PhoneNumberUtils; //导入PhoneNumberUtils类,用于处理电话号码 import android.util.Log; //导入Log类,用于输出日志 import java.util.HashMap; //导入HashMap类,用于存储电话号码和联系人名称的缓存 public class Contact { //定义一个名为Contact的类 private static HashMap sContactCache; //定义一个静态的HashMap,用于缓存电话号码和对应的联系人名称 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); } //使用PhoneNumberUtils将电话号码格式化为最小匹配格式 String selection = CALLER_ID_SELECTION.replace("+", PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); //通过ContentResolver执行查询操作,查询联系人表中的名称 Cursor cursor = context.getContentResolver().query( Data.CONTENT_URI, //查询Data内容提供者 new String [] { Phone.DISPLAY_NAME }, //查询显示名称字段 selection, //查询条件 new String[] { phoneNumber }, //查询参数,即电话号码 null); //排序条件为空 //如果查询结果不为空且有数据 if (cursor != null && cursor.moveToFirst()) { try { //获取联系人名称 String name = cursor.getString(0); //将电话号码和联系人名称缓存到HashMap中 sContactCache.put(phoneNumber, name); return name; //返回联系人名称 } catch (IndexOutOfBoundsException e) { //如果获取数据失败 Log.e(TAG, " Cursor get string error " + e.toString()); //输出错误日志 return null; //返回null表示未找到联系人 } finally { //确保查询完成后关闭游标 cursor.close(); } } else { //如果没有找到联系人 Log.d(TAG, "No contact matched with number:" + phoneNumber); //输出日志表示没有找到匹配的联系人 return null; //返回null表示未找到联系人 } } }