Android 上使用 Google 登录服务进行身份验证

添加Firebase

文档

  • 创建Firebase项目

在这里插入图片描述

  • 添加项目

在这里插入图片描述

  • 将Firebase添加到应用,按照提示一步一步的进行。

在这里插入图片描述

  • 添加SDK

    • 项目级gradle下添加
    buildscript {
        dependencies {
            classpath 'com.google.gms:google-services:4.1.0'
        }
    }
    allprojects {
        repositories {
            google() 
        }
    }
    
    • 模块级gradle下添加
    apply plugin: 'com.android.application'
    android {
    }
    dependencies {
      implementation 'com.google.firebase:firebase-core:16.0.4'
    }
    apply plugin: 'com.google.gms.google-services'
    

添加Firebase身份验证和Google登录服务

文档

  • 模块级gradle添加依赖
implementation 'com.google.firebase:firebase-auth:16.0.3'
implementation 'com.google.android.gms:play-services-auth:16.0.0'
  • 将在Firebase控制台下载的google-services.json文件放在主module目录下。

在这里插入图片描述

  • 在Firebase控制台中启用Google登录服务

在这里插入图片描述

代码

  • 开启界面,该界面会提示选择那些邮箱进行登录。R.string.client_id得去 API 控制台中的”凭据“页面,创建凭据.OAuth 2.0 客户端 ID会在你为项目添加Firebase时候自动创建好,选择Web client.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(getString(R.string.client_id)).requestEmail().build();
                        GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, gso);
                        Intent signInIntent = googleSignInClient.getSignInIntent();
                        startActivityForResult(signInIntent, RC_SIGN_IN);

在这里插入图片描述

  • 选择邮箱登录之后接受到的回调代码
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            GoogleSignInAccount result = task.getResult(ApiException.class);
            String email = result.getEmail()} catch (ApiException e) {
            ToastUtils.showLong(e.getMessage());
        }
    }
}

猜你喜欢

转载自blog.csdn.net/MoLiao2046/article/details/85851881