📅  最后修改于: 2023-12-03 14:49:48.522000             🧑  作者: Mango
Firebase 身份验证是一种用于为用户提供安全访问系统和服务的云认证解决方案。通过集成 Firebase 身份验证,您可以轻松地使用户以其 Google 帐户进行身份验证,并访问用户数据。在本文中,我们将介绍如何在 Android 应用程序中使用 Java 和 Firebase 身份验证进行 Google 签名。
要使用 Firebase 身份验证,您首先需要将 Firebase 添加到您的 Android 应用程序中。有多种方法可用于添加 Firebase,包括使用 Firebase 控制台和 Gradle。
buildscript {
dependencies {
classpath 'com.google.gms:google-services:4.3.10'
}
}
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
dependencies {
// Firebase Authentication
implementation 'com.google.firebase:firebase-auth:19.1.0'
}
要使用 Firebase 身份验证进行 Google 签名,您需要执行以下步骤:
将以下代码片段添加到您的应用程序中,以启用 Google 登录:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
将以下代码片段添加到您的应用程序中,以在应用程序中启用 Google 登录:
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
在您的活动的“onActivityResult”方法中,您应该调用 Firebase API 以验证用户并创建 Firebase 帐户。以下是这样做的示例代码:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account.getIdToken());
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
}
}
}
private void firebaseAuthWithGoogle(String idToken) {
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
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
FirebaseUser user = mAuth.getCurrentUser();
} else {
// If sign in fails, display a message to the user.
}
}
});
}
完成这些步骤后,您应该能够使用 Java 和 Firebase 身份验证进行 Google 签名。
在本文中,我们介绍了在 Android 中使用 Java 和 Firebase 身份验证进行 Google 签名的步骤。我们了解了如何添加 Firebase 到您的 Android 应用程序,并使用 Firebase 身份验证实现 Google 登录。我们希望这篇文章能够帮助您在 Android 应用程序中创建安全的登录体验。