23

I want to read the message body of a new incoming SMS in android, programmatically.

I tried something but that doesn't return any contents:

Uri uri = Uri.parse("content://sms/inbox");
        ContextWrapper context = null;      
        Cursor c = context.getContentResolver().query(uri, null, null ,null,null);      
        String body = null; 
        String number=null;
        if(c.moveToFirst()) {        
           body = c.getString(c.getColumnIndexOrThrow("body")).toString();
           number = c.getString(c.getColumnIndexOrThrow("address")).toString();
        }
        c.close(); 
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
Krishna
  • 4,892
  • 18
  • 63
  • 98
  • Good article here: http://mobdev.olin.edu/mobdevwiki/FrontPage/Tutorials/SMS%20Messaging – David d C e Freitas Oct 02 '11 at 18:35
  • http://stackoverflow.com/questions/14097500/get-inbox-messages-from-android-device-to-show-in-custom-listview# It works for me. This guy anwser here at StackOverflow – texeratx Dec 04 '15 at 13:07

5 Answers5

23

I have posted some sample programs about this on my class website. Here is the example Read SMS Example Here is a snippet of code. Basically your can register a broadcast receiver to listen for SMS_Receive and check out the following.

Intent intent = getIntent();
    Bundle bundle = intent.getBundleExtra("mySMS");

    if (bundle != null) {
        Object[] pdus = (Object[])bundle.get("pdus");
        SmsMessage sms = SmsMessage.createFromPdu((byte[])pdus[0]);
        Log.i("mobile.cs.fsu.edu", "smsActivity : SMS is <" +  sms.getMessageBody() +">");

        //strip flag
        String message = sms.getMessageBody();
        while (message.contains("FLAG"))
            message = message.replace("FLAG", "");

        TextView tx = (TextView) findViewById(R.id.TextBox);
        tx.setText(message);            
    } else
        Log.i("mobile.cs.fsu.edu", "smsActivity : NULL SMS bundle");
Frank Sposaro
  • 8,511
  • 4
  • 43
  • 64
  • There's also a static `getMessagesFromIntent(Intent)` method returning an `SmsMessage`-array (since API level 19), so manual reading/casting of the "pdus" byte-array may not be necessary if your target level is high enough: https://developer.android.com/reference/android/provider/Telephony.Sms.Intents.html#getMessagesFromIntent(android.content.Intent) – Blacklight Jan 28 '15 at 11:49
  • I have 2 sims in my phone! Is it possible to check which sim is receiving message? – Huzaifa Asif Oct 03 '19 at 07:06
6

Below is the piece of code which read the incoming message and display in the list view, don' forget to add the permission in manifest file:

<uses-permission android:name="android.permission.READ_SMS"/>

Here the code:

 listitem=(ListView)findViewById(R.id.ListView);

        Uri mSmsQueryUri = Uri.parse("content://sms/inbox");
        List<String> messages = new ArrayList<String>();

        Cursor cursor = null;
        try {
            cursor = getContentResolver().query(mSmsQueryUri, null, null, null, null);
            if (cursor == null) {
                Log.i(TAG, "cursor is null. uri: " + mSmsQueryUri);

            }
            for (boolean hasData = cursor.moveToFirst(); hasData; hasData = cursor.moveToNext()) {
                final String body = cursor.getString(cursor.getColumnIndexOrThrow("body"));
                messages.add(body);
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        } finally {
            cursor.close();
        }

        listitem.setAdapter(new ArrayAdapter<String>(ReadMessage.this, android.R.layout.simple_list_item_1,messages));
RobinHood
  • 10,897
  • 4
  • 48
  • 97
1

A very easy solution would be to use this SMS Parser library:

https://github.com/adorsys/sms-parser-android

compile 'de.adorsys.android:smsparser:0.0.3'

Using it you can either read the whole message, or specific parts of the incoming message. You can also set the phone numbers from which the message will be coming.

If you need more info about how it works or its usage check the github repository I listed above.

drilonrecica
  • 327
  • 1
  • 4
  • 19
0

Here in this example i'll demonstrate you that how to read the recent received(incoming) sms from inbox and to show it in textview.

 fstmsgBtn.setOnClickListener(new OnClickListener()

    { public void onClick(View v) 
    {
        Uri my_uri = Uri.parse("content://sms/inbox");          
        Cursor readFstSms =v.getContext().getContentResolver().query(my_uri, null, null ,null,null); 
        if(readFstSms.moveToFirst()) 
        {
           String  msg_body =  c.getString(c.getColumnIndexOrThrow("body")).toString();
           //String sender_number = c.getString(c.getColumnIndexOrThrow("address")).toString();
           readtxt.setText(msg_body);
        }
        readFstSms.close();
    }
    });
Pir Fahim Shah
  • 10,505
  • 1
  • 82
  • 81
0
listitem=(ListView)findViewById(R.id.list_view);

            Uri mSmsQueryUri = Uri.parse("content://sms/inbox");
            List<String> messages = new ArrayList<String>();

            Cursor cursor = null;
            try {
                cursor = getContentResolver().query(mSmsQueryUri, null, null, null, null);
                if (cursor == null) {
                   // Log.i(TAG, "cursor is null. uri: " + mSmsQueryUri);

                }
                for (boolean hasData = cursor.moveToFirst(); hasData; hasData = cursor.moveToNext()) {
                    final String body = cursor.getString(cursor.getColumnIndexOrThrow("body")).toString();
                    final String sender_no= cursor.getString(cursor.getColumnIndexOrThrow("address")).toString();
                    final String date= cursor.getString(cursor.getColumnIndexOrThrow("date"));
                    final String type =cursor.getString(cursor.getColumnIndexOrThrow("type"));


                    messages.add(body);
                    messages.add(sender_no);
                    messages.add(date);
                    messages.add(type);
                }
            } catch (Exception e) {
                //Log.e(TAG, e.getMessage());
            } finally {
                cursor.close();
            }

            listitem.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,messages));
     }
}
Bhoomika Brahmbhatt
  • 7,404
  • 3
  • 29
  • 44
Irfan Ali
  • 189
  • 1
  • 9