user1217055 user1217055 - 6 months ago 18
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.");
}

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


And the receiver:

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


And:

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


I start it with:

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


In the main activity.

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

Answer

Declare this in your mainfest:

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

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

}