Update Contact.java

master
p42car8zu 3 months ago
parent 42d3c4074d
commit 490c77d78b

@ -1,6 +1,6 @@
/*
* 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
@ -26,48 +26,68 @@ import android.util.Log;
import java.util.HashMap;
public class Contact {
// 缓存联系人信息的HashMap
private static HashMap<String, String> sContactCache;
// 用于日志标记的常量
private static final String TAG = "Contact";
// 定义查询电话号码对应的联系人ID的SQL语句
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 "
+ ") 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
* @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));
// 替换SQL语句中的电话号码占位符
String selection = CALLER_ID_SELECTION.replace("+", PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME },
new String[]{ Phone.DISPLAY_NAME },
selection,
new String[] { phoneNumber },
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());
// 如果获取联系人名称时发生索引越界异常则记录错误日志并返回null
Log.e(TAG, "Cursor get string error " + e.toString());
return null;
} finally {
// 关闭游标
cursor.close();
}
} else {
// 如果没有找到匹配的联系人则记录日志并返回null
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}
}
}
```
Loading…
Cancel
Save