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

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

准备工作

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

配置 Google 登录和 GoogleSignInClient 对象

  1. 在您的登录 activity 的 onCreate 方法中,将 Google 登录配置为 请求您的应用所需的用户数据。例如,要配置 登录 Google 登录以请求获取ID 和基本个人资料信息创建 GoogleSignInOptions 具有 DEFAULT_SIGN_IN 参数的对象。请求用户的电子邮件 创建 GoogleSignInOptions 对象,并在对象中 requestEmail选项。

    // 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 方法中,检查用户是否已登录

// 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 或任何适合您应用的 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. 用户登录后,您可以获得 GoogleSignInAccount 在 Activity 的 onActivityResult 方法中为用户创建对象。

    @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 获取用户的电子邮件地址, 将用户的 Google ID(供客户端使用)与 getId 结合使用; 以及具有 getIdToken 的用户的 ID 令牌。 如果您需要将当前登录的用户传递到后端服务器, 将 ID 令牌发送到您的后端服务器 并在服务器上验证令牌