Prakash Bala Prakash Bala - 4 months ago 40
Android Question

Read sms only for OTP

In my android application i am implementing auto fill OTP from SMS, I learnt from this link http://androiddhina.blogspot.in/2015/06/reading-incoming-message-automatically-to-verify-OTP.html

My doubt is

BroadcastReceiver
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
BroadcastReceiver
for particular period of time.

Answer

try this out.

private BroadcastReceiver SmsListener = new BroadcastReceiver() {

        @SuppressWarnings("deprecation")
        @Override
        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

@Override
protected void onPause() {
    super.onPause();
    YourActivity.this.unregisterReceiver(SmsListener);
};

@Override
protected void onResume() {
    super.onResume();
    IntentFilter i = new IntentFilter(
            "android.provider.Telephony.SMS_RECEIVED");
    YourActivity.this.registerReceiver(SmsListener, i);
}

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

Happy Coding.