You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
note/scr/Contact代码注释.java

70 lines
3.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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用于缓存联系人信息避免重复查询
private static HashMap<String, String> sContactCache;
// 定义一个常量TAG用于日志输出
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 = '+')";
// 定义一个静态方法getContact接收一个Context对象和一个电话号码字符串返回该电话号码对应的联系人姓名
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));
// 使用ContentResolver查询联系人数据库获取匹配给定电话号码的联系人姓名
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) {
// 如果发生异常记录日志并返回null
Log.e(TAG, " Cursor get string error " + e.toString());
return null;
} finally {
// 关闭Cursor
cursor.close();
}
} else {
// 如果没有找到匹配的联系人记录日志并返回null
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}
}
}