注释文件,源文件路径:src/net/micode/notes/data

mater
root 4 months ago
parent 8e90cb07af
commit b57ffe84c1

@ -0,0 +1,101 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* (c) 2010-2011MiCode www.micode.net
*
* Licensed under the Apache License, Version 2.0 (the "License");
* Apache 2.0
* 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 {
// 缓存电话号码与对应联系人名称,避免重复查询数据库
private static HashMap<String, String> sContactCache;
// 日志标签
private static final String TAG = "Contact";
// 查询联系人名称的SQL条件语句模板
// 功能匹配指定电话号码且数据类型为电话条目并通过phone_lookup表优化查询效率
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 = '+')"; // '+'将在运行时替换为实际最小匹配长度
/**
*
* @param context 访ContentResolver
* @param phoneNumber
* @return null
*/
public static String getContact(Context context, String phoneNumber) {
// 初始化缓存
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
// 优先从缓存中获取
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, // 内容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(); // 确保关闭Cursor释放资源
}
} else {
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}
}
}
Loading…
Cancel
Save