如何从收件箱消息中读取 "Contact Name"
How to read "Contact Name" from inbox messages
我正在使用内容提供商从收件箱中读取短信。见以下代码:
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cursor = this.getContentResolver().query(uriSms, null, null, null, SORT_ORDER);
内部循环我正在获取所有必需的列:
String body= cursor.getString(cursor.getColumnIndex("body"));
String person = cursor.getString(cursor.getColumnIndex("person"));
我正在正确获取所有值,但是 人名 正在返回 'null' 值。请指导我为什么没有从上述声明中返回联系人姓名。
试试这个:
Cursor cursor = getContentResolver().query(
uriSms,
new String[] { "_id", "thread_id", "address", "person", "date",
"body", "type" }, null, null, null);
person
列的值(如果存在)不是发件人的姓名。这是一个 ID,您可以使用它来查询 Contacts Provider 以获取姓名。如果 person
为空,则必须使用 address
(即 phone 数字)进行查询。例如:
String address = cursor.getString(cursor.getColumnIndex("address"));
final String[] projection = new String[] {ContactsContract.Data.DISPLAY_NAME};
String displayName = null;
Cursor contactCursor = null;
try {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(address));
contactCursor = getContentResolver().query(uri,
projection,
null,
null,
null);
if (contactCursor != null && contactCursor.moveToFirst()) {
displayName = contactCursor.getString(
contactCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
if(contactCursor != null) {
contactCursor.close();
}
}
我正在使用内容提供商从收件箱中读取短信。见以下代码:
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cursor = this.getContentResolver().query(uriSms, null, null, null, SORT_ORDER);
内部循环我正在获取所有必需的列:
String body= cursor.getString(cursor.getColumnIndex("body"));
String person = cursor.getString(cursor.getColumnIndex("person"));
我正在正确获取所有值,但是 人名 正在返回 'null' 值。请指导我为什么没有从上述声明中返回联系人姓名。
试试这个:
Cursor cursor = getContentResolver().query(
uriSms,
new String[] { "_id", "thread_id", "address", "person", "date",
"body", "type" }, null, null, null);
person
列的值(如果存在)不是发件人的姓名。这是一个 ID,您可以使用它来查询 Contacts Provider 以获取姓名。如果 person
为空,则必须使用 address
(即 phone 数字)进行查询。例如:
String address = cursor.getString(cursor.getColumnIndex("address"));
final String[] projection = new String[] {ContactsContract.Data.DISPLAY_NAME};
String displayName = null;
Cursor contactCursor = null;
try {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(address));
contactCursor = getContentResolver().query(uri,
projection,
null,
null,
null);
if (contactCursor != null && contactCursor.moveToFirst()) {
displayName = contactCursor.getString(
contactCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
if(contactCursor != null) {
contactCursor.close();
}
}