Lak*_*hna 1 android firebase firebase-authentication
我正在使用最新的 firebase sdk 进行身份验证,但 otp 自动填充不起作用。OTP 短信已成功接收,当我手动输入时,它工作正常,没有任何问题。但我需要自动获取 OTP,无需用户参与。
我的代码:
mAuth = FirebaseAuth.getInstance();
editText = findViewById(R.id.sixdigit);
mTextViewCountDown = findViewById(R.id.text_view_countdown);
progress = new ProgressDialog(GVerifyotpActivity.this);
progress.setMessage("Waiting....");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
String phonenumber = getIntent().getStringExtra("phonenumber");
sendVerificationCode(phonenumber);
findViewById(R.id.pnext).setOnClickListener(v -> {
String code = editText.getText().toString().trim();
if (code.isEmpty() || code.length() < 6) {
editText.setError("Enter code...");
editText.requestFocus();
return;
}
verifyCode(code);
});
mButtonStartPause = findViewById(R.id.button_start_pause);
mButtonStartPause.setOnClickListener(view -> {
resetTimer();
startTimer();
resendVerificationCode(phonenumber, mResendToken);
});
}
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
if(progress!=null && !progress.isShowing()) {
progress.show();
}
}
private void signInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
//Success!
}).addOnFailureListener(unused-> Toast.makeText(this, R.string.try_1, Toast.LENGTH_SHORT).show());
} else {
Toast.makeText(GVerifyotpActivity.this, Objects.requireNonNull(task.getException()).getMessage(), Toast.LENGTH_LONG).show();
}
});
}
private void sendVerificationCode(String number) {
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber(number) // 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 void startTimer() {
new CountDownTimer(mTimeLeftInMillis, 1000) {
@Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
@Override
public void onFinish() {
mButtonStartPause.setEnabled(true);
}
}.start();
}
private void resetTimer() {
mTimeLeftInMillis = START_TIME_IN_MILLIS;
updateCountDownText();
mButtonStartPause.setEnabled(false);
}
private void resendVerificationCode(String phoneNumber,
PhoneAuthProvider.ForceResendingToken token) {
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
.setForceResendingToken(token) // ForceResendingToken from callbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private void updateCountDownText() {
int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
mTextViewCountDown.setText(timeLeftFormatted);
}
public void testPhoneAutoRetrieve() {
// [START auth_test_phone_auto]
// The test phone number and code should be whitelisted in the console.
String phoneNumber = "+9471268xxxxx";
String smsCode = "123456";
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseAuthSettings firebaseAuthSettings = firebaseAuth.getFirebaseAuthSettings();
// Configure faking the auto-retrieval with the whitelisted numbers.
firebaseAuthSettings.setAutoRetrievedSmsCodeForPhoneNumber(phoneNumber, smsCode);
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(phoneNumber)
.setTimeout(120L, TimeUnit.SECONDS)
.setActivity(this)
.setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
// Instant verification is applied and a credential is directly returned.
// ...
Log.d("TAGRR", "onVerificationCompleted: "+credential);
}
// [START_EXCLUDE]
@Override
public void onVerificationFailed(FirebaseException e) {
Log.d("TAGRR", "onVerificationFailed: "+e);
}
// [END_EXCLUDE]
})
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
// [END auth_test_phone_auto]
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
mResendToken = forceResendingToken;
}
@Override
public void onVerificationCompleted(@NonNull PhoneAuthCredential credential) {
// This callback will be invoked in two situations:
// 1 - Instant verification. In some cases the phone number can be instantly
// verified without needing to send or enter a verification code.
// 2 - Auto-retrieval. On some devices Google Play services can automatically
// detect the incoming verification SMS and perform verification without
// user action.
Log.d("TAGP", "onVerificationCompleted:" + credential);
String code = credential.getSmsCode();
if (code != null) {
editText.setText(code);
}
signInWithCredential(credential);
if(progress!=null && !progress.isShowing()) {
progress.show();
}
}
@Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(GVerifyotpActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
};
Run Code Online (Sandbox Code Playgroud)
依赖关系
implementation 'com.google.firebase:firebase-auth:21.0.1'
implementation 'com.google.android.gms:play-services-auth-api-phone:17.5.1'
implementation 'com.google.android.gms:play-services-auth:19.2.0'
Run Code Online (Sandbox Code Playgroud)
Android DeviceCheck API 已成功添加,SHA-256 密钥已插入 Firebase 设置中!安全网已启动!
classpath 'com.android.tools.build:gradle:4.2.2'
classpath 'com.google.gms:google-services:4.3.8'
Run Code Online (Sandbox Code Playgroud)
一切都按照 Firebase 文档完成 [https://firebase.google.com/docs/auth/android/phone-auth]
我用 testPhoneAutoRetrieve() 方法进行了测试,它可以工作,但对于真正的 sim 它不起作用!凭据不会从收到的短信中获取!
找到日志
Ignoring header X-Firebase-Locale because its value was null.
FirebaseAuth: [SmsRetrieverHelper] Timed out waiting for SMS.
PhoneAuthProvider: Sms auto retrieval timed-out.
Run Code Online (Sandbox Code Playgroud)
有什么我忘记了吗?应用程序名称字符限制有什么问题吗?示例应用程序名称 - MyApp:Abc、Xyz(国家/地区)
我遇到了同样的问题,我的问题是由于应用程序名称太长而无法包含哈希码。以下是一些解决方法:
123456 是您的 %APP_NAME% 的验证码。
abc_hascode_xyz
如果您的短信末尾不包含 hashCode,您可能必须将应用程序名称缩短至不超过 15 个字符。
如果您的应用已在 Google Play 上发布,则短信中的名称将与 Google Play 商店中的名称相同。
如果您将名称更改为 15 个字符,但错误仍然存在,您可能需要等待至少 24 小时才能使更改反映在 Firebase 上。
如果经过上述操作仍然没有解决,请检查您的接收器是否在代码中配置良好。
查看关于应用名称的新 GooglePlay 政策:常见应用名称违规示例
归档时间: |
|
查看次数: |
3007 次 |
最近记录: |