将 Google 登录功能集成到您的 Android 应用中

如需将 Google 登录功能集成到您的 Android 应用中,请配置 Google 登录功能,并在应用布局中添加一个用于启动登录流程的按钮。

准备工作

配置 Google API 控制台项目并设置 Android Studio 项目

配置 Google 登录和 GoogleSignInClient 对象

  1. 在登录 activity 的 onCreate 方法中,将 Google 登录功能配置为请求应用所需的用户数据。例如,如需将 Google 登录功能配置为请求用户 ID 和基本个人资料信息,请使用 DEFAULT_SIGN_IN 参数创建 GoogleSignInOptions 对象。如果也要请求用户的电子邮件地址,请使用 requestEmail 选项创建 GoogleSignInOptions 对象。

    // Configure sign-in to request the user's ID, email address, and basic
    // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

    如果您需要请求其他范围以访问 Google API,请使用 requestScopes 指定这些范围。为了获得最佳用户体验,在登录时,请仅请求让应用实现最低限度运行所需的范围。请仅在需要时请求额外的作用域,以便用户在执行操作的上下文中看到同意屏幕。请参阅请求其他范围

  2. 然后,同样在登录 activity 的 onCreate 方法中,使用您指定的选项创建一个 GoogleSignInClient 对象。

    // Build a GoogleSignInClient with the options specified by gso.
    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

检查是否已有已登录用户

在 activity 的 onStart 方法中,检查用户是否已使用 Google 帐号登录您的应用。

// Check for existing Google Sign In account, if the user is already signed in
// the GoogleSignInAccount will be non-null.
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
updateUI(account);

如果 GoogleSignIn.getLastSignedInAccount 返回 GoogleSignInAccount 对象(而不是 null),则表示用户已通过 Google 账号登录您的应用。相应地更新界面,即隐藏登录按钮、启动主 activity 或任何适合您的应用的内容。

如果 GoogleSignIn.getLastSignedInAccount 返回 null,则表示用户尚未使用 Google 帐号登录您的应用。更新界面以显示 Google 登录按钮。

在您的应用中添加 Google 登录按钮

  1. 标准的 Google 登录按钮 在应用布局中添加 SignInButton

    <com.google.android.gms.common.SignInButton
     android:id="@+id/sign_in_button"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    
  2. 可选:如果您使用的是默认登录按钮图片,而不是提供自己的登录按钮资源,则可以使用 setSize 方法自定义按钮的大小。

    // Set the dimensions of the sign-in button.
    SignInButton signInButton = findViewById(R.id.sign_in_button);
    signInButton.setSize(SignInButton.SIZE_STANDARD);
    
  3. 在 Android activity 中(例如,在 onCreate 方法中),注册按钮的 OnClickListener,让用户只需点击该按钮即可登录:

    findViewById(R.id.sign_in_button).setOnClickListener(this);
    

启动登录流程

  1. “登录账号选择器”的图片在 activity 的 onClick 方法中,使用 getSignInIntent 方法创建登录 intent,然后使用 startActivityForResult 启动 intent,以处理登录按钮点按操作。

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_in_button:
                signIn();
                break;
            // ...
        }
    }
    
    private void signIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    启动 intent 会提示用户选择用于登录的 Google 帐号。如果您请求的范围超出了 profileemailopenid,系统还会提示用户授予对所请求资源的访问权限。

  2. 用户登录后,您可以在 activity 的 onActivityResult 方法中获取用户的 GoogleSignInAccount 对象。

    @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) {
            // The Task returned from this call is always completed, no need to attach
            // a listener.
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }

    GoogleSignInAccount 对象包含有关已登录用户的信息,例如用户的姓名。

    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
            GoogleSignInAccount account = completedTask.getResult(ApiException.class);
    
            // Signed in successfully, show authenticated UI.
            updateUI(account);
        } catch (ApiException e) {
            // The ApiException status code indicates the detailed failure reason.
            // Please refer to the GoogleSignInStatusCodes class reference for more information.
            Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
            updateUI(null);
        }
    }

    您还可以通过 getEmail 获取用户的电子邮件地址,通过 getId 获取用户的 Google ID(供客户端使用),并通过 getIdToken 获取用户的电子邮件地址。如果您需要将当前登录的用户传递给后端服务器,请将 ID 令牌发送到后端服务器,并在服务器上验证该令牌。