Android:如何从recipient_id中查找联系人姓名和号码

时间:2016-10-10 08:09:43

标签: java android android-studio contacts

我正在使用

Uri uriSms = Uri.parse("content://mms-sms/conversations?simple=true");
    Cursor cursor = getContentResolver().query(uriSms, null,null,null,null);
    cursor.moveToLast();
    while  (cursor.moveToPrevious())
    {
        String recipient_ids= cursor.getString(cursor.getColumnIndex("recipient_ids"));
        String body = cursor.getString(cursor.getColumnIndex("snippet"));

     }

获取短信对话列表。 “recipient_ids”返回一些值,如302,301 259等。我想要的是一个函数,我将“recipient_ids”作为参数传递,它将返回联系人的显示名称(如果可用,则为数字)

2 个答案:

答案 0 :(得分:0)

请检查此代码

    private void fetchInbox() {
    Uri inboxURI = Uri.parse("content://sms/inbox");
    String[] reqCols = new String[]{"_id", "address", "body"};
    ContentResolver cr = getContentResolver();
    Cursor c = cr.query(inboxURI, reqCols, null, null, null);

    adapter = new SimpleCursorAdapter(this, R.layout.row, c,
            new String[]{"body", "address"}, new int[]{
            R.id.lblMsg, R.id.lblNumber}, 0);
}

答案 1 :(得分:0)

这些方法可帮助您实现所需目标: getContactByRecipientId - 通过recipientId获取联系号码。 getContactbyPhoneNumber - 按电话号码获取显示名称。

public String getContactByRecipientId(long recipientId) {

   String contact = "";
   Uri uri = ContentUris.withAppendedId(Uri.parse("content://mms-sms/canonical-address"), recipientId);
   Cursor cursor = getContentResolver().query(uri, null, null, null, null);

   try {
     if (cursor.moveToFirst()) {
        contact = getContactbyPhoneNumber(cursor.getString(0));
    }
  } finally {
    cursor.close();
  }

  return contact;
}


public String getContactbyPhoneNumber(String phoneNumber) {

  Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
  String[] projection = {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup.NORMALIZED_NUMBER };
  Cursor cursor = getContentResolver().query(uri, projection, null, null, null);

  String name = null;
  String nPhoneNumber = phoneNumber;

  try {

    if (cursor.moveToFirst()) {
      nPhoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.NORMALIZED_NUMBER));
      name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
    }

  } finally {
    cursor.close();
  }

   if(name != null){ // if there is a display name, then return that
      return name;
   }else{
      return nPhoneNumber; // if there is not a display name, then return just phone number
   }
}