skip to Main Content

How can I solve these errors:

2021-10-04 13:53:00.422 8440-8440/com.example.firebase.sms.smsotp4 E/zzf: Problem retrieving SafetyNet Token: 7: 

2021-10-04 13:53:00.618 8440-8802/com.example.firebase.sms.smsotp4 E/FirebaseAuth: [GetAuthDomainTask] IOException occurred: java.net.UnknownHostException: Unable to resolve host "www.googleapis.com": No address associated with hostname

2021-10-04 13:53:00.725 8440-8440/com.example.firebase.sms.smsotp4 E/zzf: Failed to get reCAPTCHA token with error [An internal error has occurred.]- calling backend without app verification

2021-10-04 13:53:00.762 8440-8566/com.example.firebase.sms.smsotp4 E/FirebaseAuth: [SmsRetrieverHelper] SMS verification code request failed: unknown status code: 17020 null

When I try to send an SMS OTP Verification, these errors appear

The Project is connected with firebase


The google-services.json file is added to the Project


The phone auth in firebase is enabled


Android Device Verification API in Google Cloud Console is enabled

MainActivity.java:

package com.example.firebase.sms.smsotp4;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {
    public static CustomVP viewPager;

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

        viewPager = findViewById(R.id.view_pager);

        VPAdapter adapter = new VPAdapter(getSupportFragmentManager());

        viewPager.setAdapter(adapter);
    }

}

SendOTPCode.java:

package com.example.firebase.sms.smsotp4;

import android.app.Activity;
import android.widget.Toast;

import com.google.firebase.FirebaseException;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.auth.PhoneAuthProvider.OnVerificationStateChangedCallbacks;

import java.util.concurrent.TimeUnit;

public class SendOTPCode{
    public static boolean sended;

    public static boolean send(Activity activity, String phoneNum) {
        // Whenever verification is triggered with the whitelisted number,
        // provided it is not set for auto-retrieval, onCodeSent will be triggered.

        FirebaseAuth auth = FirebaseAuth.getInstance();
        // Configure faking the auto-retrieval with the whitelisted numbers.
        PhoneAuthOptions options = PhoneAuthOptions.newBuilder(auth)
                .setPhoneNumber(phoneNum)
                .setTimeout(1L, TimeUnit.SECONDS)
                .setActivity(activity)
                .setCallbacks(new OnVerificationStateChangedCallbacks() {
                    @Override
                    public void onCodeSent(String verificationId,
                                           PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                        // Save the verification id somewhere
                        // ...
                        SendOTPFragment.verificationId.setValue(verificationId);
                        SendOTPFragment.mBoolean = false;
                        sended = true;
                        Toast.makeText(activity.getApplicationContext(), verificationId,Toast.LENGTH_SHORT).show();
                        // The corresponding whitelisted code above should be used to complete sign-in.
                    }


                    @Override
                    public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
                        // Sign in with the credential
                        // ...
                    }

                    @Override
                    public void onVerificationFailed(FirebaseException e) {
                        // ...
                        Toast.makeText(activity.getApplicationContext(), "Something went wrong!!n Please, try again later",Toast.LENGTH_SHORT).show();
                        SendOTPFragment.verificationId.setValue("null");
                        SendOTPFragment.mBoolean = false;
                    }
                })
                .build();
        PhoneAuthProvider.verifyPhoneNumber(options);

        return sended;
    }

}

SendOTPFragment.java:

package com.example.firebase.sms.smsotp4;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;


public class SendOTPFragment extends Fragment {

    public static boolean mBoolean;
    private static String mString;
    public static MutableLiveData<String> verificationId = new MutableLiveData<>();
    private LinearLayout phoneBox;
    public static String phoneNumber;
    private EditText phone;
    private Button btnOTP;
    private Toast toast;
    private LinearLayout progress_layout;

    public SendOTPFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_send_otp, container, false);
        phone = rootView.findViewById(R.id.phone_number);
        phoneBox = rootView.findViewById(R.id.phoneBox);
        btnOTP = rootView.findViewById(R.id.btnOTP);
        progress_layout = rootView.findViewById(R.id.progress_layout);

        if(mString != null && !mBoolean) {
            phone.setText(mString);
            phone.requestFocus();
            phoneBox.setBackgroundResource(R.drawable.edit_text_back_color_focused);
        }
        if (!mBoolean) {

            phoneBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    phone.requestFocus();
                    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(phone, InputMethodManager.SHOW_IMPLICIT);
                }
            });
            btnOTP.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (phone.getText().toString().trim().isEmpty()) {
                        if (toast != null) {
                            toast.cancel();
                        }
                        toast = Toast.makeText(getActivity().getApplicationContext(), "Please Enter Your Phone Number!", Toast.LENGTH_SHORT);
                        toast.show();
                    } else if (phone.getText().length() < 10) {
                        if (toast != null) {
                            toast.cancel();
                        }
                        toast = Toast.makeText(getActivity().getApplicationContext(), "Please, Enter a valid phone number!", Toast.LENGTH_SHORT);
                        toast.show();
                    } else if (phone.getText().toString().charAt(0) == '1'
                            && (phone.getText().toString().charAt(1) == '0'
                            || phone.getText().toString().charAt(1) == '1'
                            || phone.getText().toString().charAt(1) == '2'
                            || phone.getText().toString().charAt(1) == '5')) {
                        if (toast != null) {
                            toast.cancel();
                        }
                        toast = Toast.makeText(getActivity().getApplicationContext(), "Done!", Toast.LENGTH_SHORT);
                        toast.show();
                        phone.setFocusable(false);
                        SendOTP();
                        phoneNumber = "+20" + phone.getText().toString().trim();
                    } else {
                        if (toast != null) {
                            toast.cancel();
                        }
                        toast = Toast.makeText(getActivity().getApplicationContext(), "Please, Enter a valid phone number!", Toast.LENGTH_SHORT);
                        toast.show();
                    }
                }
            });

            phone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean b) {
                    if (b) {
                        phoneBox.setBackgroundResource(R.drawable.edit_text_back_color_focused);
                    } else {
                        phoneBox.setBackgroundResource(R.drawable.edit_text_back_color);
                    }
                }
            });
            phone.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    mString = charSequence.toString();
                }

                @Override
                public void afterTextChanged(Editable editable) {

                }



            });

            phone.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {

                    if (phone.getText().toString().trim().isEmpty()) {
                        if (toast != null) {
                            toast.cancel();
                        }
                        toast = Toast.makeText(getActivity().getApplicationContext(), "Please Enter Your Phone Number!", Toast.LENGTH_SHORT);
                        toast.show();
                    } else if (phone.getText().length() < 10) {
                        if (toast != null) {
                            toast.cancel();
                        }
                        toast = Toast.makeText(getActivity().getApplicationContext(), "Please, Enter a valid phone number!", Toast.LENGTH_SHORT);
                        toast.show();
                    } else if (phone.getText().toString().charAt(0) == '1'
                            && (phone.getText().toString().charAt(1) == '0'
                            || phone.getText().toString().charAt(1) == '1'
                            || phone.getText().toString().charAt(1) == '2'
                            || phone.getText().toString().charAt(1) == '5')) {
                        if (toast != null) {
                            toast.cancel();
                        }
                        toast = Toast.makeText(getActivity().getApplicationContext(), "Done!", Toast.LENGTH_SHORT);
                        toast.show();
                        phone.setFocusable(false);
                        SendOTP();
                        phoneNumber = "+20" + phone.getText().toString().trim();
                    } else {
                        if (toast != null) {
                            toast.cancel();
                        }
                        toast = Toast.makeText(getActivity().getApplicationContext(), "Please, Enter a valid phone number!", Toast.LENGTH_SHORT);
                        toast.show();
                    }

                    return false;
                }
            });
        } else {
            SendOTP();
        }

        return rootView;
    }

    private void SendOTP() {
        phoneNumber = "+20" + phone.getText().toString().trim();
        phone.setText(mString);
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(phone.getWindowToken(), 0);
        btnOTP.setVisibility(View.GONE);
        progress_layout.setVisibility(View.VISIBLE);
        mBoolean = true;
        if (SendOTPCode.send(getActivity() ,"+20" + phone.getText().toString())){
            VerifyOTP();
        }
        else{
            verificationId.observe(getActivity(), new Observer<String>() {
                @Override
                public void onChanged(@Nullable final String newIntValue) {
                    // Update the UI, in this case, a TextView.
                    if (verificationId.getValue()!="null") {
                        VerifyOTP();
                    }
                    else {
                        phone.setText(mString);
                        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.showSoftInput(phone, InputMethodManager.SHOW_IMPLICIT);
                        btnOTP.setVisibility(View.VISIBLE);
                        progress_layout.setVisibility(View.GONE);
                        phone.setFocusable(true);
                        phone.requestFocus();
                    }
                }
            });
        }
    }

    public void VerifyOTP(){

        MainActivity.viewPager.setCurrentItem(1);

    }

    @Override
    public void onStart() {
        super.onStart();
        if (mBoolean){
            phone.setText(mString);
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(phone.getWindowToken(), 0);
            btnOTP.setVisibility(View.GONE);
            progress_layout.setVisibility(View.VISIBLE);
        }
        else{
            progress_layout.setVisibility(View.GONE);
            btnOTP.setVisibility(View.VISIBLE);
        }

    }
}

build.gradle (:app):

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}


android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.firebase.sms.smsotp4"
        minSdk 21
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    implementation 'com.google.firebase:firebase-auth:21.0.1'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

}

build.gradle(:project):

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.2"
        classpath 'com.google.gms:google-services:4.3.10'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Image(Phone Auth)

2

Answers


  1. Everything seems ok on your code. And check if you have enabled the sign-in method under Authentication in firebase.
    and Please, follow the link below for more information.

    Firebase captcha check fails and prevents user from authenticating

    Login or Signup to reply.
  2. I had the same Issue.
    For me the problem was that the device was not connected to Internet.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search