Программисты JAVA общаются здесь
Anonymous
Авторизация по телефону не работает в моем приложении для Android
Сообщение
Anonymous » 28 сен 2024, 12:59
Я создаю приложение для Android с базой данных Firebase в реальном времени на бэкэнде. в приложении у меня есть интерфейс, через который пользователи могут вводить свои номера телефонов и одноразовый пароль, полученный по SMS.
Код: Выделить всё
private FirebaseAuth mAuth;
private EditText edtPhone, edtOTP;
private String verificationId;
private String phone;
private String otp;
private FirebaseUser mUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
mAuth.setLanguageCode("en");
mAuth.useAppLanguage();
mUser=mAuth.getCurrentUser();
if (FirebaseApp.getApps(this).isEmpty()) {
FirebaseApp.initializeApp(this);
}
FirebaseAppCheck firebaseAppCheck = FirebaseAppCheck.getInstance();
firebaseAppCheck.installAppCheckProviderFactory(
DebugAppCheckProviderFactory.getInstance()
);
if (mAuth.getCurrentUser() != null) {
navigateToSchoolActivity();
return;
}
edtPhone = findViewById(R.id.idPhone);
edtOTP = findViewById(R.id.idPassword);
Button generate = findViewById(R.id.idSubmit);
Button verify= findViewById(R.id.idVerify);
generate.setOnClickListener(v -> {
phone = edtPhone.getText().toString().trim();
if (validatePhoneNumber(phone)) {
sendVerificationCode(phone);
}
});
verify.setOnClickListener(v -> {
otp = edtOTP.getText().toString().trim();
if (!TextUtils.isEmpty(otp)) {
verifyCode(otp);
} else {
showToast("Please enter OTP");
}
});
}
private boolean validatePhoneNumber(String phone) {
if (TextUtils.isEmpty(phone)) {
showToast("Enter a valid Number.");
return false;
} else if (!phone.matches("^\\+[1-9]{1}[0-9]{3,14}$")) {
showToast("Enter a valid phone number in international format (e.g., +1234567890).");
return false;
}
return true;
}
private void showToast(String message) {
Toast.makeText(a0_LoginActivity.this, message, Toast.LENGTH_SHORT).show();
}
private void navigateToSchoolActivity() {
Intent intent = new Intent(a0_LoginActivity.this, a1_SchoolActivity.class);
startActivity(intent);
finish();
}
private void sendVerificationCode(String number) {
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber(number)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(this)
.setCallbacks(mCallbacks)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private final PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks =
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken token) {
super.onCodeSent(s, token);
verificationId = s;
showToast("OTP sent successfully.");
}
@Override
public void onVerificationCompleted(@NonNull PhoneAuthCredential credential) {
signInWithCredential(credential);
}
@Override
public void onVerificationFailed(@NonNull FirebaseException e) {
Log.e("Verification Failed", "Error: " + e.getMessage());
showToast("Verification failed: " + e.getMessage());
}
};
private void verifyCode(String code) {
if (verificationId != null) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
} else {
showToast("Verification ID not found. Try again.");
}
}
private void signInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInWithCredential:success");
mUser = task.getResult().getUser();
navigateToSchoolActivity();
} else {
Log.w(TAG, "signInWithCredential:failure", task.getException());
handleAuthFailure(task);
}
}
});
}
private void handleAuthFailure(Task task) {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
showToast("Invalid OTP");
} else {
showToast("Authentication Failed");
}
}
}
Приложение отображает сообщение об ошибке о том, что этому приложению не разрешено использовать Firebase. Также отображается ошибка проверки приложения. Могу ли я получить здесь помощь?
Подробнее здесь:
https://stackoverflow.com/questions/790 ... ndroid-app
1727517563
Anonymous
Я создаю приложение для Android с базой данных Firebase в реальном времени на бэкэнде. в приложении у меня есть интерфейс, через который пользователи могут вводить свои номера телефонов и одноразовый пароль, полученный по SMS. [code] private FirebaseAuth mAuth; private EditText edtPhone, edtOTP; private String verificationId; private String phone; private String otp; private FirebaseUser mUser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); mAuth = FirebaseAuth.getInstance(); mAuth.setLanguageCode("en"); mAuth.useAppLanguage(); mUser=mAuth.getCurrentUser(); if (FirebaseApp.getApps(this).isEmpty()) { FirebaseApp.initializeApp(this); } FirebaseAppCheck firebaseAppCheck = FirebaseAppCheck.getInstance(); firebaseAppCheck.installAppCheckProviderFactory( DebugAppCheckProviderFactory.getInstance() ); if (mAuth.getCurrentUser() != null) { navigateToSchoolActivity(); return; } edtPhone = findViewById(R.id.idPhone); edtOTP = findViewById(R.id.idPassword); Button generate = findViewById(R.id.idSubmit); Button verify= findViewById(R.id.idVerify); generate.setOnClickListener(v -> { phone = edtPhone.getText().toString().trim(); if (validatePhoneNumber(phone)) { sendVerificationCode(phone); } }); verify.setOnClickListener(v -> { otp = edtOTP.getText().toString().trim(); if (!TextUtils.isEmpty(otp)) { verifyCode(otp); } else { showToast("Please enter OTP"); } }); } private boolean validatePhoneNumber(String phone) { if (TextUtils.isEmpty(phone)) { showToast("Enter a valid Number."); return false; } else if (!phone.matches("^\\+[1-9]{1}[0-9]{3,14}$")) { showToast("Enter a valid phone number in international format (e.g., +1234567890)."); return false; } return true; } private void showToast(String message) { Toast.makeText(a0_LoginActivity.this, message, Toast.LENGTH_SHORT).show(); } private void navigateToSchoolActivity() { Intent intent = new Intent(a0_LoginActivity.this, a1_SchoolActivity.class); startActivity(intent); finish(); } private void sendVerificationCode(String number) { PhoneAuthOptions options = PhoneAuthOptions.newBuilder(mAuth) .setPhoneNumber(number) .setTimeout(60L, TimeUnit.SECONDS) .setActivity(this) .setCallbacks(mCallbacks) .build(); PhoneAuthProvider.verifyPhoneNumber(options); } private final PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken token) { super.onCodeSent(s, token); verificationId = s; showToast("OTP sent successfully."); } @Override public void onVerificationCompleted(@NonNull PhoneAuthCredential credential) { signInWithCredential(credential); } @Override public void onVerificationFailed(@NonNull FirebaseException e) { Log.e("Verification Failed", "Error: " + e.getMessage()); showToast("Verification failed: " + e.getMessage()); } }; private void verifyCode(String code) { if (verificationId != null) { PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code); signInWithCredential(credential); } else { showToast("Verification ID not found. Try again."); } } private void signInWithCredential(PhoneAuthCredential credential) { mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()) { Log.d(TAG, "signInWithCredential:success"); mUser = task.getResult().getUser(); navigateToSchoolActivity(); } else { Log.w(TAG, "signInWithCredential:failure", task.getException()); handleAuthFailure(task); } } }); } private void handleAuthFailure(Task task) { if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { showToast("Invalid OTP"); } else { showToast("Authentication Failed"); } } } [/code] Приложение отображает сообщение об ошибке о том, что этому приложению не разрешено использовать Firebase. Также отображается ошибка проверки приложения. Могу ли я получить здесь помощь? Подробнее здесь: [url]https://stackoverflow.com/questions/79033915/phone-auth-login-not-working-for-my-android-app[/url]