Search sms Inbox

2019-02-11 08:31发布

问题:

How can I search the sms inbox and show latest message from a special number. For example search for "999999999" and show last message received from this number. Is any way to do this?

I have use this code to return the count of messages my inbox

TextView view;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

  view = (TextView) findViewById(R.id.textView1);

  final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
  Cursor c = getContentResolver().query(SMS_INBOX, null, null, null, null);
  int unreadMessagesCount = c.getCount();
  c.deactivate();

  view.setText(String.valueOf(unreadMessagesCount));

回答1:

If you only want the last message sent by a specific number use this:

final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(SMS_INBOX, null, "address = ?", 
        new String[] {"9999999999"}, "date desc limit 1");
if(cursor.moveToFirst()) {
    // Do something 
    Log.v("Example", cursor.getString(cursor.getColumnIndex("body")));
}
cursor.close();

The second answer to How many database columns associated with a SMS in android? is a great reference for different columns in an SMS.



回答2:

try as:

final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(SMS_INBOX,null,null, null,"DATE desc");
if(c.moveToFirst()){
        for(int i=0;i<c.getCount();i++){
          String  body= c.getString(c.getColumnIndexOrThrow("body")).toString();
          String number=c.getString(c.getColumnIndexOrThrow("address")).toString();
          if(number=="999999999")
           {
            //get message body here
                    break;
           }
           else
            c.moveToNext();
         }
  }
 c.close();