將 Google 登入整合至 Android 應用程式

如要將 Google 登入整合至 Android 應用程式,請設定 Google 登入並 在應用程式的版面配置中新增按鈕,用於啟動登入流程。

事前準備

設定 Google API 控制台專案,並設定 Android Studio 專案

設定 Google 登入和 GoogleSignInClient 物件

  1. 在登入活動的 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. 接著,在登入活動的 onCreate 方法中建立 GoogleSignInClient 物件,其中包含您指定的選項。

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

檢查目前登入的使用者

在活動的 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 登入您的應用程式。 據此更新使用者介面,也就是隱藏登入按鈕,啟動 或任何適合您的應用程式的內容。

如果 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 活動中 (例如 onCreate 方法中) 註冊 使用者按下按鈕的 OnClickListener 後即可登入:

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

啟動登入流程

  1. 登入帳戶選擇工具的圖片 在活動的 onClick 方法中,建立一個 透過 getSignInIntent 建立登入意圖 方法,並使用 startActivityForResult 啟動意圖。

    @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);
    }

    啟動意圖會提示使用者選取要登入的 Google 帳戶 。如果您要求的範圍超過 profileemailopenid, 系統也會提示使用者授予要求資源的存取權。

  2. 使用者登入後,您就能獲得 GoogleSignInAccount 物件。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 權杖傳送至後端伺服器 並驗證伺服器上的憑證