/* * 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包里面 //导入android框架中的一些类,便于数据库的管理更新等 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; //导入了标准 Java 库中的 HashMap 类。HashMap 是 Java 中的一个基本数据结构,用于存储键值对。它实现了 Map 接口,允许存储键值对,并提供了快速的数据访问方法 import java.util.HashMap; //联系人 public class Contact { private static HashMap sContactCache;//HashMap 通常被用来临时缓存联系人信息 //String 是键的类型,表示联系人的标识符或者其他唯一值。String 是值的类型,表示与联系人相关联的信息或数据。 private static final String TAG = "Contact";//private static final String定义的是一个类内部的、只能在当前类中访问、不可变的静态字符串常量 private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER //比较电话号码是否相等,Phone.NUMBER 是电话号码字段名 + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"//and逻辑与操作符,用于连接条件 + " 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是空的就创建一个 if(sContactCache.containsKey(phoneNumber)) {//查找sContactCache中是否有phoneNumber的信息 return sContactCache.get(phoneNumber);//如果有就返回如果没有就不管 } // 将电话号码的查询条件中的占位符替换为与号码匹配的最小匹配号码 String selection = CALLER_ID_SELECTION.replace("+", PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); Cursor cursor = context.getContentResolver().query( // 查找数据库中phoneNumber的信息 Data.CONTENT_URI, new String [] { Phone.DISPLAY_NAME }, selection, new String[] { phoneNumber }, null); // 如果查询到phoneNumber的信息的结果集并且结果集中有数据 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 cursor.close(); } } else { // 如果没有匹配的联系人信息,记录日志 Log.d(TAG, "No contact matched with number:" + phoneNumber); return null; } } }