/* * 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; //将该类放在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; //在util包中的一个类 public class Contact { //声明一个公有类 private static HashMap sContactCache; //一个静态的hashmap的对象,且数据类型是两个string类 private static final String TAG = "Contact"; //一个静态常量的string类型 private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" //使得MIMETYPE获得电话 + " 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是否为空 sContactCache = new HashMap();//如果为空,则为scontactcache申请空间 } if(sContactCache.containsKey(phoneNumber)) {//检查phonenumber是否存在指定的映射关系,返回一个boolean类型的数据 return sContactCache.get(phoneNumber);//返回改key所对应的value值 } String selection = CALLER_ID_SELECTION.replace("+", //replace是查找并替换,将+号用 PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); //构建一个查询时,生成后七位号码 Cursor cursor = context.getContentResolver().query( //得到一个context的对象并进行数据查询 Data.CONTENT_URI, //对应的是联系人数据表,在数据表中查找数据 new String [] { Phone.DISPLAY_NAME },//联系人名称 selection, new String[] { phoneNumber }, null); if (cursor != null && cursor.moveToFirst()) { //cursor不为空,且查询结果不为空 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(); //将cursor关闭 } } else { //没有查找到姓名 Log.d(TAG, "No contact matched with number:" + phoneNumber); //错误提示 return null; //返回空 } } }