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.
ReadMiNotes/标注/Contact.java

69 lines
2.5 KiB

1 year ago
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;
// 定义一个Contact类
public class Contact {
// 声明一个HashMap类型的静态变量sContactCache
private static HashMap<String, String> sContactCache;
// 声明一个String类型的静态变量TAG
private static final String TAG = "Contact";
// 声明一个String类型的静态变量CALLER_ID_SELECTION
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和phoneNumber
public static String getContact(Context context, String phoneNumber) {
// 如果sContactCache为空则初始化sContactCache
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,
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;
}
}
}