Firebase Phone Authen如何发送otp代码并访问另一个活动

时间:2017-08-03 07:52:22

标签: android firebase firebase-authentication

我有两个活动第一个用于输入数字的活动来检查来自firebase的发送otp代码的auth,但我需要将代码放入第二个活动中使用Textwatcher

这里我的第一个活动代码现在可以输入数字并转到第二个活动并接收Otp代码并传递给第二个活动

@Override
        public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
            Toast.makeText(OTP1.this,"verifucation done"+ phoneAuthCredential,Toast.LENGTH_LONG).show();
        }

        @Override
        public void onVerificationFailed(FirebaseException e) {
            Toast.makeText(OTP1.this,"verifucation fail",Toast.LENGTH_LONG).show();
            if (e instanceof FirebaseAuthInvalidCredentialsException) {
                // Invalid request
                // [START_EXCLUDE]
                Toast.makeText(OTP1.this,"invalid mob no",Toast.LENGTH_LONG).show();
                // [END_EXCLUDE]
            } else if (e instanceof FirebaseTooManyRequestsException) {
                // The SMS quota for the project has been exceeded
                // [START_EXCLUDE]
                Toast.makeText(OTP1.this,"quta over" ,Toast.LENGTH_LONG).show();
                // [END_EXCLUDE]
            }
        }
        @Override
        public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {
            // The SMS verification code has been sent to the provided phone number, we
            // now need to ask the user to enter the code and then construct a credential
            // by combining the code with a verification ID.
            //Log.d(TAG, "onCodeSent:" + verificationId);
            Toast.makeText(OTP1.this,"Verification code sent to mobile",Toast.LENGTH_LONG).show();
            // Save verification ID and resending token so we can use them later
            mVerificationId = verificationId;

            mResendToken = token;
            startActivity(new Intent(OTP1.this,OTP2.class));
            finish();
        }
    };

    btn_next = (ImageButton)findViewById(R.id.nextButoon);

    btn_next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PhoneAuthProvider.getInstance().verifyPhoneNumber(
                    "+66"+ put_num.getText().toString(),        // Phone number to verify
                    60,                 // Timeout duration
                    TimeUnit.SECONDS,   // Unit of timeout
                    OTP1.this,               // Activity (for callback binding)
                    mCallbacks);        // OnVerificationStateChangedCallbacks

        }
    });

}

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(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");
                        Toast.makeText(OTP1.this,"Verification done",Toast.LENGTH_LONG).show();
                        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
                            Toast.makeText(OTP1.this,"Verification failed code invalid",Toast.LENGTH_LONG).show();
                        }
                    }
                }
            });
}

这是我的第二个活动,我正在尝试使用Textwatcher的简单代码并获得此错误

08-03 14:50:34.383 7790-7790/com.example.androiddev.army31 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.androiddev.army31, PID: 7790
                                                                             java.lang.IllegalArgumentException: Given String is empty or null
                                                                                 at com.google.android.gms.common.internal.zzbo.zzcF(Unknown Source)
                                                                                 at com.google.firebase.auth.PhoneAuthCredential.<init>(Unknown Source)
                                                                                 at com.google.firebase.auth.PhoneAuthProvider.getCredential(Unknown Source)
                                                                                 at com.example.androiddev.army31.LoginScreen.OTP2$1.onTextChanged(OTP2.java:57)
                                                                                 at android.widget.TextView.sendOnTextChanged(TextView.java:8504)
                                                                                 at android.widget.TextView.handleTextChanged(TextView.java:8566)
                                                                                 at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:10770)
                                                                                 at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:1212)
                                                                                 at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:582)
                                                                                 at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:509)
                                                                                 at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:508)
                                                                                 at android.text.method.NumberKeyListener.onKeyDown(NumberKeyListener.java:121)
                                                                                 at android.widget.TextView.doKeyDown(TextView.java:6528)
                                                                                 at android.widget.TextView.onKeyDown(TextView.java:6318)
                                                                                 at android.view.KeyEvent.dispatch(KeyEvent.java:2740)
                                                                                 at android.view.View.dispatchKeyEvent(View.java:9948)

这是我的第二项活动

pinView.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (pinView.getText().toString().trim().length() == 6){
                PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, pinView.getText().toString());
                signInWithPhoneAuthCredential(credential);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });





}

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(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");
                        Toast.makeText(OTP2.this,"Verification done",Toast.LENGTH_LONG).show();
                        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
                            Toast.makeText(OTP2.this,"Verification failed code invalid",Toast.LENGTH_LONG).show();
                        }
                    }
                }
            });
}

1 个答案:

答案 0 :(得分:1)

我的问题是我的google_services.json中的api_key值为空。这是因为firebase为我生成的默认json文件根本没有api_key值,所以我只是手动添加一个以使其工作。在此处添加随机字符串值将使codelab工作,但请确保停止当前运行并重建项目,否则Android Studio自动运行功能将在不更新正在使用的json文件的情况下运行。

你可以从中获取你的api密钥。 /console.firebase.google.com/project - &gt;你的项目 - &gt;设置 - &gt;一般。

并将其添加到google_services.json current_key