Google 로그인을 Android 앱에 통합하려면 Google 로그인을 구성하고 앱의 레이아웃에 로그인 과정을 시작하는 버튼을 추가합니다.
시작하기 전에
Google API 콘솔 프로젝트를 구성하고 Android 스튜디오 프로젝트를 설정합니다.
Google 로그인 및 GoogleSignInClient 객체 구성
로그인 활동의
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
을 사용하여 지정합니다. 최상의 사용자 환경을 제공하려면 로그인 시 앱이 최소한으로 작동하는 데 필요한 범위만 요청하세요. 필요한 경우에만 추가 범위를 요청하여 사용자가 실행한 작업의 컨텍스트에서 동의 화면을 볼 수 있도록 합니다. 추가 범위 요청을 참고하세요.그런 다음 로그인 활동의
onCreate
메서드에서 지정된 옵션으로GoogleSignInClient
객체를 만듭니다.// Build a GoogleSignInClient with the options specified by gso. mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
기존 로그인 사용자 확인
활동의 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
가 null
가 아닌 GoogleSignInAccount
객체를 반환하면 사용자가 이미 Google로 앱에 로그인한 것입니다.
그에 따라 UI를 업데이트합니다. 즉, 로그인 버튼을 숨기거나 기본 활동을 실행하거나 앱에 적합한 것을 업데이트합니다.
GoogleSignIn.getLastSignedInAccount
가 null
를 반환하면 사용자가 아직 Google을 통해 앱에 로그인하지 않은 것입니다. Google 로그인 버튼을 표시하도록 UI를 업데이트합니다.
앱에 Google 로그인 버튼 추가
애플리케이션 레이아웃에
SignInButton
를 추가합니다.<com.google.android.gms.common.SignInButton android:id="@+id/sign_in_button" android:layout_width="wrap_content" android:layout_height="wrap_content" />
선택사항: 자체 로그인 버튼 애셋을 제공하는 대신 기본 로그인 버튼 그래픽을 사용하는 경우
setSize
메서드를 사용하여 버튼의 크기를 맞춤설정할 수 있습니다.// Set the dimensions of the sign-in button. SignInButton signInButton = findViewById(R.id.sign_in_button); signInButton.setSize(SignInButton.SIZE_STANDARD);
Android 활동 (예:
onCreate
메서드)에서 사용자가 클릭했을 때 로그인하도록 버튼의OnClickListener
를 등록합니다.findViewById(R.id.sign_in_button).setOnClickListener(this);
로그인 흐름 시작
활동의
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 계정을 선택하라는 메시지가 사용자에게 표시됩니다.
profile
,email
,openid
이외의 범위를 요청한 경우 사용자에게 요청된 리소스에 대한 액세스 권한을 부여하라는 메시지도 표시됩니다.사용자가 로그인하면 활동의
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 토큰을 가져올 수도 있습니다. 현재 로그인한 사용자를 백엔드 서버로 전달해야 하는 경우 ID 토큰을 백엔드 서버로 전송하고 서버에서 토큰의 유효성을 검사합니다.