1

I am using SMS Retriever API to get OTP but the problem I am facing is that it is not receiving SMS every time. Sometime SMS content is retrieved and some time nothing happens.

I have used the Toast (Broadcaster started) to show if it is started every time but Toast is also not displayed every time. I am unable to diagnose the problem.

Broadcast Receiver code:

public class OTPBroadcastReceiver extends BroadcastReceiver {
private String otp;
private static OTPSMSReceiveListner otpsmsReceiveListner = null;
private final Pattern p = Pattern.compile("(|^)\\d{4}");

public static void injectListner(OTPSMSReceiveListner listner){
    otpsmsReceiveListner = listner;
}
@Override
public void onReceive(Context context, Intent intent) {
    try {
        Toast.makeText(context,"Broadcaster started",Toast.LENGTH_LONG).show();
        if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
            Bundle extras = intent.getExtras();
            Status status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);

            switch (status.getStatusCode()) {
                case CommonStatusCodes.SUCCESS:
                    //Toast.makeText(context,"success",Toast.LENGTH_LONG).show();
                    // Get SMS message contents
                    String message = (String) extras.get(SmsRetriever.EXTRA_SMS_MESSAGE);
                    if (message != null) {
                        Matcher m = p.matcher(message);
                        if (m.find()) {
                            otp = m.group(0);
                        }
                        String token;
                        try {
                            token = CommonMethods.getSecurePref("OTP", context);
                        } catch (Exception ex) {
                            token = null;
                        }
                        if (token == null) {
                            //Pass on the text to our listener.
                            otpsmsReceiveListner.onOTPReceived(otp);
                        }
                    }
                    break;
                case CommonStatusCodes.TIMEOUT:
                    Log.d("onReceive", "timed out (5 minutes)");
                    //Toast.makeText(context,"Timeout",Toast.LENGTH_LONG).show();
                    otpsmsReceiveListner.onOTPTimeout();
                    break;
            }
        }
    }
    catch (Exception ex){
        Toast.makeText(context,ex.getLocalizedMessage(),Toast.LENGTH_LONG).show();
    }
}

public interface OTPSMSReceiveListner{
    void onOTPReceived(String otp);
    void onOTPTimeout();
}
}

OTP class:

SmsRetrieverClient client = SmsRetriever.getClient(mContext);
    Task<Void> task = client.startSmsRetriever();
    task.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            try
            {
                Log.e("onSuccess","Successfully started retriever");
            }
            catch (Exception ex)
            {
                Log.e("onSuccess",ex.getMessage());
            }
        }
    });

    task.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.e("onFailure", "Failed to start retriever");
        }
    });


    OTPBroadcastReceiver.injectListner(new OTPBroadcastReceiver.OTPSMSReceiveListner() {
        @Override
        public void onOTPReceived(String otp) {
            if(otp.length() == 4) {
                otpField.setText(otp);
                btnVerify.performClick();
            }
        }

        @Override
        public void onOTPTimeout() {
            Log.e("onOTPTimeout","onOTPTimeout");
        }
    });

Manifest:

<receiver
        android:name=".helpers.OTPBroadcastReceiver"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED" />
        </intent-filter>
    </receiver>

SMS:

<#> your App OTP is:8149 585dyDy8cbh
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mohsin
  • 902
  • 3
  • 23
  • 49
  • Shouldn't you be using `` instead of ``? – Pedro Oliveira Feb 28 '19 at 18:25
  • @PedroOliveira sorry its a typo – Mohsin Feb 28 '19 at 18:27
  • Try this: Change your opening `intent-filter` tag to this: `` – Pedro Oliveira Feb 28 '19 at 18:30
  • @PedroOliveira ive already tried it but still the problem is same – Mohsin Feb 28 '19 at 18:32
  • Are you trying to receive an SMS 5min after the you start the application? Because from what I remember, this receiver only lasts for 5min. If you want to receive another OTP you have to register and start a new one before that – Pedro Oliveira Feb 28 '19 at 18:35
  • @PedroOliveira what i am doing is. i login into the App after that i waits for OTP sometime it gets OTP sometimes not. if i get OTP i logout the app and try to login again it and wait for OTP. if i got OTP in first login attempt then i was unable to get it second time if failed first time OTP is capture second time. a very anonymous behaviour. – Mohsin Mar 01 '19 at 06:10
  • Don't declare the receiver in your manifest. Instead start it by code whenever you need to receive the otp – Pedro Oliveira Mar 01 '19 at 09:26

1 Answers1

0

See this answer https://stackoverflow.com/a/55374780/10449332. Please register the BroadcastReceiver inside SmsRetriever addOnSuccessListener callback.

deepak raj
  • 3,331
  • 1
  • 12
  • 20