Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

android - Using new Telephony content provider to read SMS

According to the 4.4 SMS APIs, the new version provides functionality to:

allow apps to read and write SMS and MMS messages on the device

I can't find any information on this functionality, nor any samples in the new SDK. This is what I have so far for reading new incoming messages.

However, I would like to read existing messages stored on the deivce:

// Can I only listen for incoming SMS, or can I read existing stored SMS?
SmsMessage[] smsList = Telephony.Sms.Intents.getMessagesFromIntent(intent);
for(SmsMessage sms : smsList) {
    Log.d("Test", sms.getMessageBody())
}

Please note: I know about using the SMS Content Provider, however this method is unsupported. According to the linked APIs, I should be able to do this in a supported way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks like you would be able to use this class to get it working. The package is Telephony.Sms.Conversations.

Although the following code uses the content provider method, this is now an official API added in API Level 19 (KitKat) for reading the SMS messages.

public List<String> getAllSmsFromProvider() {
  List<String> lstSms = new ArrayList<String>();
  ContentResolver cr = mActivity.getContentResolver();

  Cursor c = cr.query(Telephony.Sms.Inbox.CONTENT_URI, // Official CONTENT_URI from docs
                      new String[] { Telephony.Sms.Inbox.BODY }, // Select body text
                      null,
                      null,
                      Telephony.Sms.Inbox.DEFAULT_SORT_ORDER); // Default sort order

  int totalSMS = c.getCount();

  if (c.moveToFirst()) {
      for (int i = 0; i < totalSMS; i++) {
          lstSms.add(c.getString(0));
          c.moveToNext();
      }
  } else {
      throw new RuntimeException("You have no SMS in Inbox"); 
  }
  c.close();

  return lstSms;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...