使用Java在 Android 中使用 Firebase 身份验证进行 Google 签名
Firebase 是一个移动和 Web 应用程序开发平台。它提供 Web 应用程序或移动应用程序可能需要的服务。 Firebase 提供电子邮件和密码身份验证,无需为用户身份验证构建后端的任何开销。 Google 登录是一种在您的应用中对用户进行身份验证的安全方式。它减少了用户处理和处理这些额外密码以获得应用程序身份验证的麻烦。 Firebase 提供了大量选项来在您的应用中实现登录,例如电子邮件、电话号码、谷歌、Facebook 等。
我们将在本文中构建什么?
这是我们将在本文中构建的示例视频。请注意,我们将使用Java语言来制作此应用程序。
分步实施
步骤 1. 创建一个新项目
- 打开一个新项目。
- 我们将使用Java语言开发 Empty Activity。保持所有其他选项不变。
- 在您方便的时候命名应用程序。
- 将有两个名为 activity_main.xml 和 MainActivity 的默认文件。Java
如果您不知道如何在 Android Studio 中创建新项目,可以参考如何在 Android Studio 中创建/启动新项目?
第 2 步:将 Firebase 与我们的应用程序连接起来
- 导航到网站 https://firebase.google.com。
- 转到控制台。
- 添加项目
为您的项目命名并单击继续,然后将您的 Firebase 连接到您的 Google 帐户。
工程完成后会出现如下界面——
现在输入包名称和应用程序的名称。要输入 SHA-1 值,请按照以下步骤操作 - 转到 Gradle > 任务 > android > 签名报告
打开签名报告后,您将获得 SHA-1 的值,如下所示。复制它并在firebase中使用它。
完成上述步骤后,下载那里提供的 google-services.json 配置文件并将其粘贴到 android studio 中。导航到 project > app > src 并粘贴它。
去认证。
转到登录方法并启用谷歌登录。
步骤 3. 添加所需的依赖项和插件
导航到 Gradle Scripts > build.gradle(project) 并在其中添加以下依赖项-
classpath 'com.google.gms:google-services:4.3.10'
导航到 Gradle Scripts > build.gradle(module) 并在其中添加以下插件-
apply plugin: 'com.google.gms.google-services'
导航到 Gradle Scripts > build.gradle(module) 并在其中添加以下依赖项-
implementation 'com.google.firebase:firebase-auth:19.4.0'
implementation 'com.google.android.gms:play-services-auth:18.1.0'
implementation 'com.github.bumptech.glide:glide:4.11.0'
步骤 4. 添加 Internet 权限
转到 AndroidManifest.xml 文件并将以下代码添加到其中 -
步骤 5. 使用 XML 文件
导航到 app > res > layout > activity_main.xml 并将以下代码添加到该文件。下面是activity_main.xml文件的代码。
XML
XML
Java
package com.example.googlesigninfirebase;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
public class MainActivity extends AppCompatActivity {
// Initialize variables
SignInButton btSignIn;
GoogleSignInClient googleSignInClient;
FirebaseAuth firebaseAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Assign variable
btSignIn=findViewById(R.id.bt_sign_in);
// Initialize sign in options
// the client-id is copied form
// google-services.json file
GoogleSignInOptions googleSignInOptions=new GoogleSignInOptions.Builder(
GoogleSignInOptions.DEFAULT_SIGN_IN
).requestIdToken("438431947620-ecpi41uk3dhhf4mv8g8q993k3vs49ltm.apps.googleusercontent.com")
.requestEmail()
.build();
// Initialize sign in client
googleSignInClient= GoogleSignIn.getClient(MainActivity.this
,googleSignInOptions);
btSignIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Initialize sign in intent
Intent intent=googleSignInClient.getSignInIntent();
// Start activity for result
startActivityForResult(intent,100);
}
});
// Initialize firebase auth
firebaseAuth=FirebaseAuth.getInstance();
// Initialize firebase user
FirebaseUser firebaseUser=firebaseAuth.getCurrentUser();
// Check condition
if(firebaseUser!=null)
{
// When user already sign in
// redirect to profile activity
startActivity(new Intent(MainActivity.this,ProfileActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check condition
if(requestCode==100)
{
// When request code is equal to 100
// Initialize task
Task signInAccountTask=GoogleSignIn
.getSignedInAccountFromIntent(data);
// check condition
if(signInAccountTask.isSuccessful())
{
// When google sign in successful
// Initialize string
String s="Google sign in successful";
// Display Toast
displayToast(s);
// Initialize sign in account
try {
// Initialize sign in account
GoogleSignInAccount googleSignInAccount=signInAccountTask
.getResult(ApiException.class);
// Check condition
if(googleSignInAccount!=null)
{
// When sign in account is not equal to null
// Initialize auth credential
AuthCredential authCredential= GoogleAuthProvider
.getCredential(googleSignInAccount.getIdToken()
,null);
// Check credential
firebaseAuth.signInWithCredential(authCredential)
.addOnCompleteListener(this, new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
// Check condition
if(task.isSuccessful())
{
// When task is successful
// Redirect to profile activity
startActivity(new Intent(MainActivity.this
,ProfileActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
// Display Toast
displayToast("Firebase authentication successful");
}
else
{
// When task is unsuccessful
// Display Toast
displayToast("Authentication Failed :"+task.getException()
.getMessage());
}
}
});
}
}
catch (ApiException e)
{
e.printStackTrace();
}
}
}
}
private void displayToast(String s) {
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show();
}
}
Java
package com.example.googlesigninfirebase;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class ProfileActivity extends AppCompatActivity {
// Initialize variable
ImageView ivImage;
TextView tvName;
Button btLogout;
FirebaseAuth firebaseAuth;
GoogleSignInClient googleSignInClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
// Assign variable
ivImage=findViewById(R.id.iv_image);
tvName=findViewById(R.id.tv_name);
btLogout=findViewById(R.id.bt_logout);
// Initialize firebase auth
firebaseAuth=FirebaseAuth.getInstance();
// Initialize firebase user
FirebaseUser firebaseUser=firebaseAuth.getCurrentUser();
// Check condition
if(firebaseUser!=null)
{
// When firebase user is not equal to null
// Set image on image view
Glide.with(ProfileActivity.this)
.load(firebaseUser.getPhotoUrl())
.into(ivImage);
// set name on text view
tvName.setText(firebaseUser.getDisplayName());
}
// Initialize sign in client
googleSignInClient= GoogleSignIn.getClient(ProfileActivity.this
, GoogleSignInOptions.DEFAULT_SIGN_IN);
btLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Sign out from google
googleSignInClient.signOut().addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
// Check condition
if(task.isSuccessful())
{
// When task is successful
// Sign out from firebase
firebaseAuth.signOut();
// Display Toast
Toast.makeText(getApplicationContext(), "Logout successful", Toast.LENGTH_SHORT).show();
// Finish activity
finish();
}
}
});
}
});
}
}
导航到应用程序 > 右键单击 > 新建 > 活动 > 空活动并将其命名为 ProfileActivity。在activity_profile.xml文件中使用以下代码 -
XML
步骤 6. 使用Java文件
转到MainActivity。 Java文件并参考以下代码。下面是 MainActivity 的代码。 Java文件。代码中添加了注释以更详细地理解代码。
Java
package com.example.googlesigninfirebase;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
public class MainActivity extends AppCompatActivity {
// Initialize variables
SignInButton btSignIn;
GoogleSignInClient googleSignInClient;
FirebaseAuth firebaseAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Assign variable
btSignIn=findViewById(R.id.bt_sign_in);
// Initialize sign in options
// the client-id is copied form
// google-services.json file
GoogleSignInOptions googleSignInOptions=new GoogleSignInOptions.Builder(
GoogleSignInOptions.DEFAULT_SIGN_IN
).requestIdToken("438431947620-ecpi41uk3dhhf4mv8g8q993k3vs49ltm.apps.googleusercontent.com")
.requestEmail()
.build();
// Initialize sign in client
googleSignInClient= GoogleSignIn.getClient(MainActivity.this
,googleSignInOptions);
btSignIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Initialize sign in intent
Intent intent=googleSignInClient.getSignInIntent();
// Start activity for result
startActivityForResult(intent,100);
}
});
// Initialize firebase auth
firebaseAuth=FirebaseAuth.getInstance();
// Initialize firebase user
FirebaseUser firebaseUser=firebaseAuth.getCurrentUser();
// Check condition
if(firebaseUser!=null)
{
// When user already sign in
// redirect to profile activity
startActivity(new Intent(MainActivity.this,ProfileActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check condition
if(requestCode==100)
{
// When request code is equal to 100
// Initialize task
Task signInAccountTask=GoogleSignIn
.getSignedInAccountFromIntent(data);
// check condition
if(signInAccountTask.isSuccessful())
{
// When google sign in successful
// Initialize string
String s="Google sign in successful";
// Display Toast
displayToast(s);
// Initialize sign in account
try {
// Initialize sign in account
GoogleSignInAccount googleSignInAccount=signInAccountTask
.getResult(ApiException.class);
// Check condition
if(googleSignInAccount!=null)
{
// When sign in account is not equal to null
// Initialize auth credential
AuthCredential authCredential= GoogleAuthProvider
.getCredential(googleSignInAccount.getIdToken()
,null);
// Check credential
firebaseAuth.signInWithCredential(authCredential)
.addOnCompleteListener(this, new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
// Check condition
if(task.isSuccessful())
{
// When task is successful
// Redirect to profile activity
startActivity(new Intent(MainActivity.this
,ProfileActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
// Display Toast
displayToast("Firebase authentication successful");
}
else
{
// When task is unsuccessful
// Display Toast
displayToast("Authentication Failed :"+task.getException()
.getMessage());
}
}
});
}
}
catch (ApiException e)
{
e.printStackTrace();
}
}
}
}
private void displayToast(String s) {
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show();
}
}
去 ProfileActivity。 Java文件并在其中使用以下代码-
Java
package com.example.googlesigninfirebase;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class ProfileActivity extends AppCompatActivity {
// Initialize variable
ImageView ivImage;
TextView tvName;
Button btLogout;
FirebaseAuth firebaseAuth;
GoogleSignInClient googleSignInClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
// Assign variable
ivImage=findViewById(R.id.iv_image);
tvName=findViewById(R.id.tv_name);
btLogout=findViewById(R.id.bt_logout);
// Initialize firebase auth
firebaseAuth=FirebaseAuth.getInstance();
// Initialize firebase user
FirebaseUser firebaseUser=firebaseAuth.getCurrentUser();
// Check condition
if(firebaseUser!=null)
{
// When firebase user is not equal to null
// Set image on image view
Glide.with(ProfileActivity.this)
.load(firebaseUser.getPhotoUrl())
.into(ivImage);
// set name on text view
tvName.setText(firebaseUser.getDisplayName());
}
// Initialize sign in client
googleSignInClient= GoogleSignIn.getClient(ProfileActivity.this
, GoogleSignInOptions.DEFAULT_SIGN_IN);
btLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Sign out from google
googleSignInClient.signOut().addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
// Check condition
if(task.isSuccessful())
{
// When task is successful
// Sign out from firebase
firebaseAuth.signOut();
// Display Toast
Toast.makeText(getApplicationContext(), "Logout successful", Toast.LENGTH_SHORT).show();
// Finish activity
finish();
}
}
});
}
});
}
}
这是我们应用程序的最终输出。
输出:
此外,您可以看到用户的内部 Firebase 数据正在存储 -