集成Google登录

准备工作

  1. 在firbase控制台添加项目;
  • 进入firbase官网,点击右上角“转控制台”


    集成Google登录_第1张图片
    1.png
  • 选择添加项目,在弹窗中填写项目名称后创建项目


    集成Google登录_第2张图片
    2.png

    集成Google登录_第3张图片
    3.png
  • 选择您要添加的应用类型,这里我的是android;


    集成Google登录_第4张图片
    4.png
  • 在弹框中填入应用的包名,应用别名(选填)和调试签名证书SHA1(选填),如何生成SHA1请参考https://www.jianshu.com/p/a152b5789651
    集成Google登录_第5张图片
    5.png
  • 应用创建完成后下载google-services.json
    集成Google登录_第6张图片
    6.png
  • 在项目设置中可以查看之前配置的信息


    集成Google登录_第7张图片
    7.png
  1. 配置app-level build.gradle
apply plugin: 'com.android.application'
...
dependencies {
    compile 'com.google.firebase:firebase-messaging:11.0.4'
    compile 'com.google.android.gms:play-services:11.0.4'
}
apply plugin: 'com.google.gms.google-services'
  1. 配置project-level build.gradle
classpath 'com.google.gms:google-services:3.1.0'

代码集成

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
private void googleSignIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }
    }

    private void handleSignInResult(GoogleSignInResult result) {
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();
            mLoginId.setText(acct.getId() + "\n" + acct.getDisplayName() + "\n" + acct.getEmail());
        } else {
            mLoginId.setText("获取失败");
        }
    }

到此在项目中集成Google登录已经完成,当然firbase还有许多其他功能,在此简单的列举一下,有兴趣的童鞋可以研究学习;

  • 云消息传递(Firebase Cloud Messaging)
  • 身份验证(Firebase Authentication)
  • 实时数据库(Firebase Realtime Database)
  • 存储(Firebase Storage)
  • 托管(Firebase Hosting)
  • 远程配置(Firebase Remote Config)
  • 测试实验室(Firebase Test Lab for Android)
  • 奔溃报告(Firebase Crash Reporting)

你可能感兴趣的:(集成Google登录)