Search code examples
androidandroid-manifestmessage

Retrieve all inbox messages of device in android


I am using this code.

Object[] pduArray = (Object[]) intent.getExtras().get("pdus"); 

SmsMessage[] messages = new SmsMessage[pduArray.length]; 

StringBuilder messageText = new StringBuilder();

for (int i = 0; i < pduArray.length; i++) {                 
     messages[i] = SmsMessage.createFromPdu((byte[])pduArray [i]);              
     messageText.append(messages[i].getMessageBody());          
} 

But this code is for only intimate when sms is received in a device but my need is to retrieve all inbox messages which is saved in android device in android how can I do it?


Solution

  • Try this code :

       Uri SMSURI = Uri.parse("content://sms/inbox");
       String[] projection = new String[]{"_id", "address", "body", "date"};
       Cursor cursor = null;
    
       try {
            cursor = getContentResolver().query(SMSURI
                    , projection
                    , null //selection
                    , null //selectionArgs
                    , null); //sortOrder
    
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    int    id    = cursor.getInt(cursor.getColumnIndex("_id"));
                    String address = cursor.getString(cursor.getColumnIndex("address"));
                    String body = cursor.getString(cursor.getColumnIndex("body"));
                    String date = cursor.getString(cursor.getColumnIndex("date"));
    
                    Toast.makeText(getBaseContext(), "Message is >>"+body, 
                                Toast.LENGTH_SHORT).show();
                    }
    
                } while (cursor.moveToNext());
            }
    
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }