0

How do you retrieve all the sms messages from a specific contact?

I seen ways to retrieve all sms messages and then filter down to the person in particular. But I want to query using the contact id/phone number.

I'm querying the contact using ContactsContract.CommonDataKinds.Phone.NUMBER. But that string doesn't seem to match the address format in Telephony.Sms.Inbox.ADDRESS.

One number has parenthesis and dashes while the others don't.

Is this always the case? If not, what is the best way to query for all sms messages if you already have the contact ID ?

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
dumbkam
  • 379
  • 3
  • 11

1 Answers1

0

There are many ways to accomplish this, but the best way would be to find the thread-id of the conversation thread with that contact/number, and then query the thread-id for all messages.

Note that there are a lot of issues with different API levels, devices with dual-sim, mms/sms messages, etc.

Query for all threads (with their thread-id):

// This projection is suitable for API-19 and above only
String[] projection = { Threads._ID, Threads.RECIPIENT_IDS, "sort_index", Threads.SNIPPET }
Uri uri = Threads.CONTENT_URI.buildUpon().appendQueryParameter("simple", "true").build();
Cursor cur = getContentResolver().query(uri, projection, selection, null, "sort_index" + " DESC");

To translate between a RecipientId and a phone number, you can copy Android's RecipientIdCache class to your project. It's a singleton class used for converting id to number.

Query for all messages by thread-id:

// This projection is suitable for API-19 and above only
String[] projection = new String[]{
   MmsSms.TYPE_DISCRIMINATOR_COLUMN, 
   Telephony.Sms._ID, 
   Telephony.Sms.BODY, 
   "sort_index", 
   Telephony.Sms.DATE_SENT
};
Uri uri = ContentUris.withAppendedId(Threads.CONTENT_URI, id);
Cursor cur = getContentResolver().query(uri, projection, null, null, null);
marmor
  • 27,641
  • 11
  • 107
  • 150
  • Is recipientId is the same value ContactsContract.Contacts._ID? Because that's what I have. The user chooses a from a list of contact and I have to read all the sms for that contact. Also RecipientIdCache uses content://mms-sms/canonical-address and content://mms-sms/canonical-addresses. What is the differences between those two? – dumbkam May 25 '17 at 05:06
  • No, a contact-id is not the recipient-id, and recipient-id is a unique id per sms conversation, an sms conversation can be made with contacts, phone-numbers that are not contacts, a group of phone-numbers, and special non-phone addresses like "GOOGLE" (which is a valid sms address) – marmor May 28 '17 at 08:15