【问题标题】:Android app crashes on firebase phone authenticationAndroid 应用程序在 Firebase 手机身份验证时崩溃
【发布时间】:2018-10-21 17:18:47
【问题描述】:

我正在使用 firebase 进行电话号码身份验证。当我使用我的电话号码时,它会自动验证它。但是当我使用另一个电话号码时,我得到 classCastException。它说 "getGoogleApiForMethod( ) 返回 Gms"。stackoverflow Link 中存在类似问题。答案是在手机或模拟器中降级 firebase 或 google play 服务。我在下面也包含了 gradle。请检查它

例外:

W/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzal@c2c24f7
05-11 15:00:05.597 29282-29282/ W/System.err: java.lang.ClassCastException: Otp.OtpCodeFrag cannot be cast to java.util.concurrent.Executor
05-11 15:00:05.607 29282-29282/ W/System.err:     at Otp.OtpCodeFrag.signInWithPhoneAuthCredential(OtpCodeFrag.java:402)
        at Otp.OtpCodeFrag.access$200(OtpCodeFrag.java:39)
        Otp.OtpCodeFrag$2.onClick(OtpCodeFrag.java:222)
        at android.view.View.performClick(View.java:5716)
        at android.widget.TextView.performClick(TextView.java:10926)
        at android.view.View$PerformClick.run(View.java:22596)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7325)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

OTPFrag.java:

        onVerificationStateChangedCallbacks=new PhoneAuthProvider.OnVerificationStateChangedCallbacks()
                    {
                        @Override
                        public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential)
                        {
                            phoneauthCredential = phoneAuthCredential;
                            automatic_verification = true;

                            Toast.makeText(getContext(), "Verification Completed", Toast.LENGTH_SHORT).show();

                        }
                        @Override
                        public void onVerificationFailed(FirebaseException e) {
                            Toast.makeText(getContext(),"Verification Failed",Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }

                        @Override
                        public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken)
                        {
                            super.onCodeSent(s, forceResendingToken);
                            Toast.makeText(getContext(),"CodeSent",Toast.LENGTH_SHORT).show();
                            verificationid=s;
                            codesent=true;
                            token=forceResendingToken.toString();
                            Log.e("Token",token);
                            Log.e("ID",s);
        //                           smscode=phoneauthCredential.getSmsCode();
                        }
                        };

                    PhoneAuthProvider.getInstance().verifyPhoneNumber(
                        phonenumber,        // Phone number to verify
                        4,                 // Timeout duration
                        TimeUnit.SECONDS,   // Unit of timeout
                        getActivity(),               // Activity (for callback binding)
                        onVerificationStateChangedCallbacks);

    otpCodeLytBinding.verifyOtp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {

                code1=otpCodeLytBinding.cd1.getText().toString();
                code2=otpCodeLytBinding.cd2.getText().toString();
                code3=otpCodeLytBinding.cd3.getText().toString();
                code4=otpCodeLytBinding.cd4.getText().toString();
                code5=otpCodeLytBinding.cd5.getText().toString();
                code6=otpCodeLytBinding.cd6.getText().toString();
                   if (code1!=null&&!code1.equals("")&&code2!=null&&
                   !code2.equals("")&&code3!=null&&!code3.equals("")
                   &&code4!=null&&!code4.equals("")&&code5!=null
                   &&!code5.equals("")&&code6!=null&&!code6.equals(""))
               {
                   completecode=code1+code2+code3+code4+code5+code6;
                   Log.e("cm",completecode);
                   try {
                       if (verificationid!=null&&completecode!=null){

                           PhoneAuthCredential credential = PhoneAuthProvider.
                               getCredential(verificationid, completecode);
                           signInWithPhoneAuthCredential(credential);
                       }
                       else {
                           Toast.makeText(getContext(),"Something null",Toast.LENGTH_SHORT).show();
                       }
                   }
                   catch (Exception e)
                   {
                       e.printStackTrace();
                   }

               }
               else {
                       Toast.makeText(getContext(),"Please enter otp",Toast.LENGTH_SHORT).show();
                   }
            }
        });
     private void signInWithPhoneAuthCredential(PhoneAuthCredential credential)
        {
            Log.e("SigningIn","Started");
            mAuth.signInWithCredential(credential)
                    .addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {
                                // Sign in success, update UI with the signed-in user's information
    //                            Log.d(TAG, "signInWithCredential:success");
    //
    //                            FirebaseUser user = task.getResult().getUser();
                                                          }
 else {
                                // Sign in failed, display a message and update the UI
                                Log.w(TAG, "signInWithCredential:failure", task.getException());
                                if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                                    // The verification code entered was invalid
                                }
                            }
                        }
                    });
        }

build.gradle(app):

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.root5solutions.loc8official"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled = true
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    implementation 'com.balysv:material-ripple:1.0.2'

//    implementation 'com.appolica:flubber:1.0.1'
    implementation 'com.google.firebase:firebase-core:15.0.2'
    implementation 'com.google.firebase:firebase-auth:15.1.0'
    testImplementation 'junit:junit:4.12'
//    androidTestImplementation 'com.android.support.test:runner:1.0.2'
//    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
apply plugin: 'com.google.gms.google-services'

build.gradle(项目):

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.1'
        classpath 'com.google.gms:google-services:3.2.0'



        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            url "https://maven.google.com" // Google's Maven repository
        }
    }
}

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

【问题讨论】:

    标签: android firebase firebase-authentication


    【解决方案1】:

    我不知道你想用这条线做什么:

    .addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {
    

    this 转换为Executor 似乎没有意义。你想要的而不是this 是对当前活动的引用。请尝试使用getActivity() 来获取此参考。

    【讨论】:

      【解决方案2】:

      如果您不需要引用 Activity,则将 (Executor) this 替换为以下代码:

      new Executor() {
          @Override
          public void execute(Runnable command) {}
      }
      

      【讨论】:

        【解决方案3】:

        我来晚了,但它对我有用,使用

        mAuth.signInWithCredential(credential)
                    .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {
                                FirebaseUser user = Objects.requireNonNull(task.getResult()).getUser();
                                // handel success
                            } else if (task.isCanceled()){
                               // handel error
                            }
                        }
                    });
        

        而不是使用

         mAuth.signInWithCredential(credential)
                        .addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                if (task.isSuccessful()) {
                                    // Sign in success, update UI with the signed-in user's information
        //                            Log.d(TAG, "signInWithCredential:success");
        //
        //                            FirebaseUser user = task.getResult().getUser();
                                                              } else {
                                    // Sign in failed, display a message and update the UI
                                    Log.w(TAG, "signInWithCredential:failure", task.getException());
                                    if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                                        // The verification code entered was invalid
                                    }
                                }
                            }
                        });
        

        我认为(Executer)this 上下文造成了问题尝试删除它,不仅仅是Executer,而且任何上下文都会产生错误,我不知道为什么..

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-02-16
          • 1970-01-01
          • 2020-06-08
          • 2021-04-26
          • 2022-11-24
          • 2019-12-20
          相关资源
          最近更新 更多