Google+ 登录

1.准备工作
首先得在谷歌开发控制台https://console.developers.google.com 创建自己的项目,并配好相关的信息,如图

Google+ 登录_第1张图片
Paste_Image.png

2.在你的project的gradle注入谷歌服务的依赖 classpath 'com.google.gms:google-services:3.0.0'

Google+ 登录_第2张图片
Paste_Image.png

然后在你的app的gradle中加入compile 'com.google.android.gms:play-services-auth:9.6.1'依赖, 并在最底部引入apply plugin: 'com.google.gms.google-services'

Google+ 登录_第3张图片
Paste_Image.png

记得在app目录下的加入google-services.json文件

Google+ 登录_第4张图片
Paste_Image.png

好了,配置基本完成,接下来就是在你的登陆页面撸登陆的代码了
1.初始化Google 可以参考谷歌官方api https://developers.google.com/+/mobile/android/getting-started

/**
     * Google登录初始化
     */
    public void initGooglePlus() {
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestId()
                .requestProfile()
                .requestEmail()
                .build();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
    }

点击登陆按钮

/**
     * 登陆
     */
    public void googleSignIn() {
        Intent intent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(intent, G_SIGN_IN);

    }

回调

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == G_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }
    }

获取回调返回的用户相关信息

 /**
     * Google plus 登陆回调
     */
    private void handleSignInResult(GoogleSignInResult result) {
        showLog("handleSignInResult----" + result.isSuccess());
        if (result.isSuccess()) {
            GoogleSignInAccount account = result.getSignInAccount();
            showLog("id--------" + account.getId() + "----name----" + account.getDisplayName() + "---photo--" + account.getPhotoUrl());
        }
    }

好了,简单的完成google登陆了,不过还有退出等逻辑,这里就不写了

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