Tushar Korde
Tushar Korde

Reputation: 1187

How to read content of new SMS in android?

I'm new to Android development. I need to read OTP code from SMS. I searched a lot, many pepoples suggesting to use Broadcast Receiver. But no one provided exact working code.

Upvotes: 1

Views: 246

Answers (3)

Tushar Korde
Tushar Korde

Reputation: 1187

After many attempts I found an easy solution for this. Used BroadcastReceiver inside activity itself. Hope this helps someone else too.

First Register broadcast receiver in OnCreate/onResume methods.

public class SignUpActivity extends Activity {
EditText txtOTP;

private BroadcastReceiver receiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_signup);

    txtOTP = (EditText) this.findViewById(R.id.txtOTP);

    IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            Object[] pdusObj = (Object[]) bundle.get("pdus");

            String otp = "";
            for (int i = 0; i < pdusObj.length; i++) {

                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                //After getting SMS content user your own logic to retrieve OTP.
                String message = currentMessage.getDisplayMessageBody();
                if (!message.equals("") && message.contains("is your one time password")) {
                    otp = message.substring(0, 5);
                }
            }
            txtOTP.setText(otp);
        }

    };
    registerReceiver(receiver,intentFilter);

}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(receiver);
}

}

Here to retrieve OTP from SMS you can use your own logic. In my case first 5 charater was my otp. So I used substring

Also dont forgot to unregister it inside onDestroy() method.

Upvotes: 2

Shivanshu Verma
Shivanshu Verma

Reputation: 601

first of all you create a receiver class and register it in manifest.xml then whenever a new sms is received onReceive gets called. check the sms format as per your requirement and split it with otp. then pass splitted value to your activity method . if you have any doubt feel free to ask.

package com.test.Helper;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Build;
    import android.provider.Telephony;
    import android.support.v4.content.LocalBroadcastManager;
    import android.telephony.SmsMessage;
    import android.util.Log;


    /**
     * Created by user on 29/2/16.
     */
    public class SmsListener extends BroadcastReceiver {

        private LoginActivity login;

        @Override
        public void  onReceive(Context context, Intent intent) {

            if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
                        String  messageBody = smsMessage.getMessageBody();
                          try{
                        if(messageBody.contains("OTP")){
                            String[] tokens = messageBody.split("[:]+");
                            String code =tokens[0].trim();
                            login.instance.automatic_confirmotp(code); //your actvity method
                        }else {
                            Log.d(Constants.TAG, String.valueOf(messageBody));}
                        }catch (Exception e){

                         }
                    }
                }
            }
        }

    }

and register SmsListener in manifest.xml

<receiver android:name=".Activity.Helper.SmsListener">
            <intent-filter android:priority="2147483647">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

Upvotes: -1

Baoyang
Baoyang

Reputation: 36

First, you need to use a BroadcastReceiver to listen to new sms.

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

Then, in you BroadcastReceiver, you can get all the info from the intent.

public class SMSBroadcastReceiver extends BroadcastReceiver {
    @Override 
    public void onReceive(Context context, Intent intent) {

        Object[] pdus = (Object[]) intent.getExtras().get("pdus");

        for (Object p : pdus){
            byte[] sms = (byte[]) p;

            SmsMessage message = SmsMessage.createFromPdu(sms);

            String content = message.getMessageBody();//message content
            String number = message.getOriginatingAddress();
        }
    }
}

Upvotes: 0

Related Questions