How to read the message content of a new in coming message in android?

Krishna picture Krishna · Feb 15, 2011 · Viewed 43.7k times · Source

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(); 

Answer

Frank Sposaro picture Frank Sposaro · Feb 15, 2011

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");