当前位置: 首页 > 知识库问答 >
问题:

使用firebase在Android Studio中验证OTP时应用程序崩溃

萧元徽
2023-03-14

我试图在Android Studio中建立一个OTP系统,我想出了下面给出的代码,然而,每次我尝试将OTP发送到我的电话号码时,应用程序都崩溃了。代码如下:

Signp3RDClass.java

public class Signup3rdClass extends AppCompatActivity {

    TextInputLayout phoneNumber;
    CountryCodePicker countryCodePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_signup3rd_class);

        //Hooks
        countryCodePicker = findViewById(R.id.country_code_picker);
        phoneNumber = findViewById(R.id.signup_phone_number);
    }

    public void callVerifyOTPScreen(View view) {

        if (!validatePhoneNumber()) {
            return;
        }

        Intent intent = new Intent(getApplicationContext(), VerifyOTP.class);

        String _fullName = getIntent().getStringExtra("fullname");
        String _username = getIntent().getStringExtra("username");
        String _email = getIntent().getStringExtra("email");
        String _password = getIntent().getStringExtra("password");
        String _gender = getIntent().getStringExtra("gender");
        String _date = getIntent().getStringExtra("date");

        String _getUserPhoneNumber = phoneNumber.getEditText().getText().toString().trim();
        String _phoneNo = "+" + countryCodePicker.getFullNumber() + _getUserPhoneNumber;

        intent.putExtra("fullName", _fullName);
        intent.putExtra("username", _username);
        intent.putExtra("email", _email);
        intent.putExtra("password", _password);
        intent.putExtra("date", _date);
        intent.putExtra("gender", _gender);
        intent.putExtra("phoneNo", _phoneNo);

        startActivity(intent);
    }

    private boolean validatePhoneNumber() {
        String val = phoneNumber.getEditText().getText().toString().trim();
        String checkNo = "[7-9][0-9]{9}";

        if (val.isEmpty()) {
            phoneNumber.setError("Enter valid Phone Number!");
            return false;
        } else if (!val.matches(checkNo)) {
            phoneNumber.setError("Enter valid Phone Number!");
            return false;
        } else {
            phoneNumber.setError(null);
            phoneNumber.setErrorEnabled(false);
            return true;
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Common.LoginSingup.Signup3rdClass"
android:background="@color/offwhite">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="30dp"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/signup_back_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:src="@drawable/back_btn"
        android:transitionName="transition_back_btn"/>

    <TextView
        android:id="@+id/create_account"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:fontFamily="sans-serif-medium"
        android:text="@string/create_account"
        android:textAllCaps="true"
        android:textColor="@color/black"
        android:textSize="40sp"
        android:transitionName="transition_title_text"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginTop="40dp">


        <com.hbb20.CountryCodePicker
            android:id="@+id/country_code_picker"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            app:ccp_autoDetectCountry="true"
            app:ccp_showFlag="true"
            app:ccp_showNameCode="true"
            app:ccp_showFullName="true"
            android:background="@drawable/black_border"/>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/signup_phone_number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:startIconDrawable="@drawable/field_phone_number_icon"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            app:hintTextColor="@color/black"
            app:endIconMode="clear_text"
            app:endIconTint="@color/black"
            app:boxStrokeWidthFocused="2dp"
            app:boxStrokeColor="@color/black">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/enter_phone_no"/>

        </com.google.android.material.textfield.TextInputLayout>

    </LinearLayout>

    <Button
        android:id="@+id/signup_next_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/otp_code_btn"
        android:layout_marginTop="20dp"
        android:onClick="callVerifyOTPScreen"
        android:elevation="5dp"
        android:background="@color/colorPrimaryDark"
        android:textColor="@color/white"
        android:fontFamily="@font/montserrat_regular"
        android:textSize="20sp"
        android:transitionName="transition_next_btn"/>


    <Button
        android:id="@+id/signup_login_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/login"
        android:layout_marginTop="20dp"
        android:elevation="5dp"
        android:background="@color/transparant"
        android:fontFamily="@font/montserrat_regular"
        android:textSize="20sp"
        android:textColor="@color/black"
        android:transitionName="transition_login_btn"/>


</LinearLayout>
public class VerifyOTP extends AppCompatActivity {

PinView pinFromUser;
String codeBySystem;
FirebaseAuth mAuth;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_verify_o_t_p);

    pinFromUser = findViewById(R.id.pin_view);

    String _phoneNumber = getIntent().getStringExtra("phoneNo");

    mAuth = FirebaseAuth.getInstance();

    sendVerificationCodeToUser(_phoneNumber);
}

private void sendVerificationCodeToUser(String phoneNumber) {

    PhoneAuthOptions options =
            PhoneAuthOptions.newBuilder(mAuth)
                    .setPhoneNumber(phoneNumber)       // Phone number to verify
                    .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
                    .setActivity(this)                 // Activity (for callback binding)
                    .setCallbacks(mCallbacks)          // OnVerificationStateChangedCallbacks
                    .build();
    PhoneAuthProvider.verifyPhoneNumber(options);
}

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

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

            @Override
            public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
                String code = phoneAuthCredential.getSmsCode();
                if(code != null){
                    pinFromUser.setText(code);
                    verifyCode(code);
                }
            }

            @Override
            public void onVerificationFailed(@NonNull FirebaseException e) {
                Toast.makeText(VerifyOTP.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        };

private void verifyCode(String code) {
    PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codeBySystem, 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()) {

                        Toast.makeText(VerifyOTP.this, "Verification Completed!", Toast.LENGTH_SHORT).show();

                    } else {

                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            Toast.makeText(VerifyOTP.this, "Verification failed! Please try again", Toast.LENGTH_LONG).show();
                        }
                    }
                }
            });
}
E/CCP: getFullNumber: Could not parse number
I/Timeline: Timeline: Activity_launch_request time:218578976

W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@a4a9614

E/zza: Problem retrieving SafetyNet Token: 7: 
I/Timeline: Timeline: Activity_launch_request time:218581077
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@5459e2f
W/xample.desikha: Accessing hidden method Lsun/misc/Unsafe;->getInt(Ljava/lang/Object;J)I (greylist, linking, allowed)

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.desikhao, PID: 19549
java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/browser/customtabs/CustomTabsIntent$Builder;
    at com.google.firebase.auth.internal.RecaptchaActivity.zza(com.google.firebase:firebase-auth@@20.0.0:92)
    at com.google.firebase.auth.api.internal.zzeq.zza(com.google.firebase:firebase-auth@@20.0.0:79)
    at com.google.firebase.auth.api.internal.zzeq.onPostExecute(com.google.firebase:firebase-auth@@20.0.0:88)
    at android.os.AsyncTask.finish(AsyncTask.java:755)
    at android.os.AsyncTask.access$900(AsyncTask.java:192)
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:224)
    at android.app.ActivityThread.main(ActivityThread.java:7562)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
 Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.browser.customtabs.CustomTabsIntent$Builder" on path: DexPathList[[zip file "/data/app/com.example.desikhao-Z6Qez6I7lCc14bx6bjFINg==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.desikhao-Z6Qez6I7lCc14bx6bjFINg==/lib/arm64, /system/lib64, /system/product/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:230)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at com.google.firebase.auth.internal.RecaptchaActivity.zza(com.google.firebase:firebase-auth@@20.0.0:92) 
    at com.google.firebase.auth.api.internal.zzeq.zza(com.google.firebase:firebase-auth@@20.0.0:79) 
    at com.google.firebase.auth.api.internal.zzeq.onPostExecute(com.google.firebase:firebase-auth@@20.0.0:88) 
    at android.os.AsyncTask.finish(AsyncTask.java:755) 
    at android.os.AsyncTask.access$900(AsyncTask.java:192) 
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772) 
    at android.os.Handler.dispatchMessage(Handler.java:107) 
    at android.os.Looper.loop(Looper.java:224) 
    at android.app.ActivityThread.main(ActivityThread.java:7562) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 

共有1个答案

秦禄
2023-03-14

在build.gradle(:app)中实现“androidx.browser:browser:1.2.0”

 类似资料:
  • 这是代码- 启动应用程序时出错-01-13 17:07:13.543 5027-5058/com。实例金纳里。trial2 D/FA:日志记录事件(FE):用户参与(\u e),捆绑[{firebase\u event\u origin(\u o)=自动,参与时间\u毫秒(\u et)=2716,firebase\u screen\u class(\u sc)=主活动,firebase\u scr

  • 我正在尝试设置OTP验证,所以当用户输入他们的电话号码时,我会向他们发送pin码,调用,我会收到代码pin,但问题是当调用时,我想转到另一个活动,用户可以输入代码pin进行验证,但根本不会调用,我不明白为什么。任何帮助都将不胜感激,谢谢。

  • 我正在寻找一种方法来查找从Firebase电话身份验证发送给我的代码,因为我想手动验证该代码。现在的问题是Firebase正在自动检测短信并调用onVerficationComplted(),但我有一个按钮,我想手动输入otp代码并验证。下面是我的代码。如果有任何帮助,将不胜感激。谢谢

  • 我的应用/构建。格雷德尔: 在调试模式下,我成功地完成了auth。由Firebase授权。 输入电话号码 好的。工作正常。 但当我想在发布模式下执行此操作时,我会遇到下一个错误:

  • 我想用SafetyNet验证电话号码Firebase,而不是重新CAPTCHA验证。我在这里遵循Firebase留档:https://firebase.google.com/docs/auth/android/phone-auth 在谷歌API控制台中,我启用了Android设备验证API 在Firebase控制台中,我添加了SHA-256指纹 重新安装谷歌服务。json并将其添加到项目中 它总是

  • 03-29 19:26:37.449 176 02-17602/com.developerillusion.hive e/androidruntime:致命异常:main process:com.developerillusion.hive,pid:17602 java.lang.runtimeexception:无法启动活动ComponentInfo{com.developerillusion.