短信验证码请求失败:未知状态码:17020 null

问题描述 投票:0回答:3

如何解决这些错误:

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

当我尝试发送短信 OTP 验证时,出现这些错误

该项目已与firebase连接


google-services.json 文件已添加到项目中


Firebase 中的电话身份验证已启用


Google Cloud Console 中的 Android 设备验证 API 已启用

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);
    }

}

发送OTPCode.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;
    }

}

发送OTPFragment.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(:应用程序):

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(:项目):

// 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)

java android android-studio firebase-authentication logcat
3个回答
0
投票

您的代码似乎一切正常。并检查您是否已在 firebase 中的身份验证下启用登录方法。 请点击下面的链接了解更多信息。

Firebase 验证码检查失败并阻止用户进行身份验证


0
投票

我遇到了这个问题。我所做的就是禁用验证方法,然后再次启用它。为我工作!!


-1
投票

我也有同样的问题。 对我来说,问题是设备未连接到互联网。

© www.soinside.com 2019 - 2024. All rights reserved.