/* * 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; public class Contact { //联系人数据库 /*hashmap是一系列的键-值队(以键查找值),hashmap的特点是:无序,键不重复 是泛型的概念,这里意思是,键是字符串,值也是字符串*/ 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); } //toCallerIDMinMatch是安卓自带的号码匹配工具,截取查询号码的后7位作为匹配依据 String selection = CALLER_ID_SELECTION.replace("+", PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); //cursor类是对数据库的操作,获取整行的数据,从数据库中查询联系人内容 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; } } }