Prakash Bala Prakash Bala - 1 year ago 116
Android Question

Read sms only for OTP

In my android application i am implementing auto fill OTP from SMS, I learnt from this link

My doubt is

reads every sms received by the user, can we stop this? I need to read sms at a particular time Example: only after user clicks the send OTP button after that I should stop reading sms.

Please help me how to start and stop the
for particular period of time.

Answer Source

try this out.

private BroadcastReceiver SmsListener = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            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();
                            // do your stuff
                    } catch (Exception e) {
                        // Log.d("Exception caught",e.getMessage());

and as per i did

protected void onPause() {

protected void onResume() {
    IntentFilter i = new IntentFilter(
    YourActivity.this.registerReceiver(SmsListener, i);

but as others suggested you can register BroadcastReceiver after request for OTP and unregistered after getting OTP.

Happy Coding.

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