Using new Telephony content provider to read SMS

后端 未结 3 1836
死守一世寂寞
死守一世寂寞 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:21

    I did it like the following. Create SMSObject:

    public class SMSObject {
      private String _id;
      private String _address;
      private String _msg;
      private String _readState; // "0" for have not read sms and "1" for have
                                // read sms
      private String _time;
      private String _folderName;
    
      //+ getter and setter methods and 
    
      @Override
      public String toString() {
        return "SMSObject [_id=" + _id + ", _address=" + _address + ", _msg="
                + _msg + ", _readState=" + _readState + ", _time=" + _time
                + ", _folderName=" + _folderName + "]";
    }
    

    And here a simple function, which simply logs all current SMS-Objects

    private void readSMS() {
        List lstSms = new ArrayList();
        SMSObject objSms = new SMSObject();
        Uri message = Uri.parse("content://sms/");
        ContentResolver cr = this.getContentResolver();
    
        Cursor c = cr.query(message, null, null, null, null);
        // this.startManagingCursor(c);
        int totalSMS = c.getCount();
        Log.d("SMS Count->", "" + totalSMS);
        if (c.moveToFirst()) {
            for (int i = 0; i < totalSMS; i++) {
    
                objSms = new SMSObject();
                objSms.setId(c.getString(c.getColumnIndexOrThrow("_id")));
                objSms.setAddress(c.getString(c
                        .getColumnIndexOrThrow("address")));
                objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
                objSms.setReadState(c.getString(c.getColumnIndex("read")));
                objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
                if (c.getString(c.getColumnIndexOrThrow("type")).contains("1")) {
                    objSms.setFolderName("inbox");
                } else {
                    objSms.setFolderName("sent");
                }
    
                lstSms.add(objSms);
    
                Log.d("SMS at " + i, objSms.toString());
    
                c.moveToNext();
            }
        }
        // else {
        // throw new RuntimeException("You have no SMS");
        // }
        c.close();
    
        // return lstSms;
    
    }
    

提交回复
热议问题