user1217055 user1217055 - 1 year ago 97
Android Question

Read an incomming SMS in Android

I've got a BroadcastReceiver in my app:

public class SMSReceiver extends BroadcastReceiver {

public void onCreate(){
Log.i("APP","SMS Receiver started.");

public void onReceive(Context context, Intent intent) {
Log.i("APP", "SMS received.");

And the receiver:

<receiver class="SMSReceiver" android:name=".SMSReceiver" >
<action android:name="smsreceiver" android:value="android.provider.Telephony.SMS_RECEIVED" />


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

I start it with:

Intent SMS = new Intent(this, SMSReceiver.class);

In the main activity.

How can I read the content of the messages? Thanks.

Answer Source

Declare this in your mainfest:

<receiver android:name=".SMSReceiver"> 
        <intent-filter android:priority="100"> 
            <action android:name=
                "android.provider.Telephony.SMS_RECEIVED" /> 

No need to start your receiver from intent when you declare it in manifest, it is automatically called when incoming message arrives.

And here is code for broadcast receiver:

Put this code in your onRecieve method

 if (!intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) 
                        bundle = intent.getExtras();

            if (bundle != null) {
                // ---retrieve the SMS message received---
                Object[] pdus = (Object[]) bundle.get("pdus");
                // Set<String> Bundle.keySet();
                msgs = new SmsMessage[pdus.length];
                // DeleteSMSFromInbox(context, msgs);
                for (int i = 0; i < msgs.length; i++) {

                    msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    ClsIncomingsmsNo = msgs[i].getOriginatingAddress();
                    System.out.println("ClsIncomingsmsNo" + ClsIncomingsmsNo);
                    msg = msgs[i].getMessageBody().toString();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download