receiver下:
方法1:
public static String getContactNameByAddr(Context context, String phoneNumber) {
String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
//
ContentResolver cr = context.getContentResolver();
//
Cursor cursor = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, // Which columns to return.
ContactsContract.CommonDataKinds.Phone.NUMBER + " = '"
+ phoneNumber + "'", // WHERE clause.
null, // WHERE clause value substitution
null); // Sort order.
if (cursor == null) {
Log.d(TAG, "getPeople null");
return null;
}
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
// 取得联系人名字
int nameFieldColumnIndex = cursor
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
String name = cursor.getString(nameFieldColumnIndex);
Log.v(TAG, name);
return name;
}
return phoneNumber;
}
方法2:
public static String getContactNameByAddr(Context context,String phoneNumber) {
Uri personUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
Cursor cur = context.getContentResolver().query(personUri, new String[] { PhoneLookup.
DISPLAY_NAME }, null, null, null);
if (cur.moveToFirst()) {
int nameIdx = cur.getColumnIndex(PhoneLookup.DISPLAY_NAME);
String name = cur.getString(nameIdx);
cur.close();
return name;
}
return phoneNumber;
}
activity下:
public static String getContactNameByAddr(String phoneNumber) {
String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
//
ContentResolver cr = getContentResolver();
//
Cursor cursor = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, // Which columns to return.
ContactsContract.CommonDataKinds.Phone.NUMBER + " = '"
+ phoneNumber + "'", // WHERE clause.
null, // WHERE clause value substitution
null); // Sort order.
if (cursor == null) {
Log.d(TAG, "getPeople null");
return null;
}
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
// 取得联系人名字
int nameFieldColumnIndex = cursor
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
String name = cursor.getString(nameFieldColumnIndex);
Log.v(TAG, name);
return name;
}
return phoneNumber;
}
注意:要在AndroidManifest.xml中添加权限
阅读(1479) | 评论(0) | 转发(0) |