How to read SMS code from your android App

Bulu picture Bulu · Jun 10, 2016 · Viewed 9.8k times · Source

We are looking to build the functionality in our app to read a security code that being sent as part of SMS and display on the textView. Also, I am not looking to build a broadcast receiver, may be an intent service which only will start run on a particular screen and kill the service once user navigated to another screen.

It would be great if anyone can shade some light and help with some sample code.

Answer

Sohail Zahid picture Sohail Zahid · Jun 10, 2016

To read incoming SMS you have to do three things.

  1. Broadcast Receiver
  2. Declare Broadcast Receiver in manifest
  3. Need SMS Receive permissions

Note: If you are compiling against 6.0 Marshmallow you have get android.permission.RECEIVE_SMS at runtime. Runtime Permissions

Lets Starts Receiving incoming SMS

1) First add permissions in manifest

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

2) Declare Broadcast Receiver in Manifest.

What this declaration do it will inform you when ever a new SMS Receive by device.

<receiver android:name="com.example.abc.ReciveSMS">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

3) Add this code to your declared class in manifest

public class ReciveSMS extends BroadcastReceiver{

    private SharedPreferences preferences;

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
            Bundle bundle = intent.getExtras();           //---get the SMS message passed in---
            SmsMessage[] msgs = null;
            String msg_from;
            if (bundle != null){
                //---retrieve the SMS message received---
                try{
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    msgs = new SmsMessage[pdus.length];
                    for(int i=0; i<msgs.length; i++){
                        msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        msg_from = msgs[i].getOriginatingAddress();
                        String msgBody = msgs[i].getMessageBody();
                    }
                }catch(Exception e){
//                            Log.d("Exception caught",e.getMessage());
                }
            }
        }
    }
}

Original Post here.