Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Firebase Phone Auth Not Receiving SMS Second Time

Hi I am trying to do a phone auth in android using firebase. The first time I install the app the sms comes and verification is successful but subsequently the sms does not come again. I have deleted the user from the auth in firebase and still it is not working.

Following is my code.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    CountryCodePicker ccp;

    EditText editTextPhone, editTextCode;

    FirebaseAuth mAuth;

    String codeSent;

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

        mAuth = FirebaseAuth.getInstance();

        editTextCode = findViewById(R.id.editTextCode);
        editTextPhone = findViewById(R.id.editTextPhone);

        findViewById(R.id.buttonGetVerificationCode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendVerificationCode();
            }
        });

        findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                verifySignInCode();
            }
        });
    }

    private void verifySignInCode() {
        String code = editTextCode.getText().toString();
        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codeSent, code);
        signInWithPhoneAuthCredential(credential);
    }

    private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            //here you can open new activity
                            Toast.makeText(getApplicationContext(),
                                    "Login Successfull", Toast.LENGTH_LONG).show();
                        } else {
                            if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                                Toast.makeText(getApplicationContext(),
                                        "Incorrect Verification Code ", Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                });
    }

    private void sendVerificationCode() {

        String phone = editTextPhone.getText().toString();

        if (phone.isEmpty()) {
            editTextPhone.setError("Phone number is required");
            editTextPhone.requestFocus();
            return;
        }

        if (phone.length() < 6 || phone.length() > 13) {
            editTextPhone.setError("Please enter a valid phone");
            editTextPhone.requestFocus();
            return;
        }

        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                phone,        // Phone number to verify
                60,                 // Timeout duration
                TimeUnit.SECONDS,   // Unit of timeout
                this,               // Activity (for callback binding)
                mCallbacks);        // OnVerificationStateChangedCallbacks

        Toast.makeText(MainActivity.this,
                "SMS Sent, Please Wait....", Toast.LENGTH_LONG).show();

        editTextCode.requestFocus();

    }

    PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

        @Override
        public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {

        }

        @Override
        public void onVerificationFailed(FirebaseException e) {

        }

        @Override
        public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
            super.onCodeSent(s, forceResendingToken);

            codeSent = s;
        }
    };

}

EDIT restarting the phone allows resending the sms after the 60 second timeout set in the function above. So it seems the phone is keeping something in the memory.

like image 601
DragonFire Avatar asked May 26 '18 00:05

DragonFire


People also ask

How do I get Firebase OTP?

In the Firebase console, open the Authentication section. In the Sign in method tab, enable the Phone provider if you haven't already. Open the Phone numbers for testing accordion menu. Provide the phone number you want to test, for example: +1 650-555-3434.

How much OTP is free in Firebase?

Limitations of OTP in firebase: The free plan of firebase has Ten Thousand Verification per month, but if you exceed this limit, you need to pay for that.

How do I use Firebase authentication on my phone?

Authenticate with Firebase on Android using a Phone Number. You can use Firebase Authentication to sign in a user by sending an SMS message to the user's phone. The user signs in using a one-time code contained in the SMS message.

Why does Firebase limit the number of SMS messages I can send?

To prevent abuse, Firebase enforces a limit on the number of SMS messages that can be sent to a single phone number within a period of time. If you exceed this limit, phone number verification requests might be throttled.

How to connect firebase to Android Studio?

After creating a new project in Android Studio connect your app to Firebase. For connecting your app to firebase. Navigate to Tools on the top bar. After that click on Firebase. A new window will open on the right side.

What happens when I send a fictional phone number to Firebase?

When you provide the fictional phone number and send the verification code, no actual SMS is sent. Instead, you need to provide the previously configured verification code to complete the sign in. On sign-in completion, a Firebase user is created with that phone number.


2 Answers

In case someone is not getting the concept or reason of not sent sms again then please go through on my below details. I have been confused for very long time that why I didn't get sms for second time, third and so on..

First Read the original documentation:

onVerificationCompleted(PhoneAuthCredential)

This method is called in two situations:

  • Instant verification: in some cases the phone number can be instantly verified without needing to send or enter a verification code.
  • Auto-retrieval: on some devices, Google Play services can automatically detect the incoming verification SMS and perform verification without user action. (This capability might be unavailable with some carriers.)

What I found:

onVerificationCompleted:

is only called when instant verification or auto-retrieval occurs.

When you try this for the first time you will get the otp code from Google but the next time you try it, it can cause instant verification to get active.

You can do:

So if you are debugging and having problem with not receiving otp code from google just disable your sim card and enable it again. This will help you in getting the otp codes from google again for one more time until you enter your code and instant verification gets activated again

Please note:

I don't think there is any way you can disable instant verification as of now. But you can always optimize your code in a way it doesn't create any problem for you and your users.

If you want to explore more then please check the thread: Click here

like image 85
Shahzad Afridi Avatar answered Oct 16 '22 21:10

Shahzad Afridi


In my case, I have my number on

Phone numbers for testing (optional)

Removing it from there, firebase started sending SMS Code to my number. Spark Plan offer 10k phone auth per month. So that you can test and deploy your app without paying a penny.

like image 10
Kashif Avatar answered Oct 16 '22 20:10

Kashif