Using new Telephony content provider to read SMS

后端 未结 3 1839
死守一世寂寞
死守一世寂寞 2020-12-02 19:23

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

3条回答
  •  伪装坚强ぢ
    2020-12-02 20:03

    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 getAllSmsFromProvider() {
      List lstSms = new ArrayList();
      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;
    }
    

提交回复
热议问题