[android] Google Sign In 코드 짜기 #2
https://developers.google.com/identity/sign-in/android/sign-in
GoogleSignInApi ref doc.
-
sign-in activity 의 onCreate 에서 GoogleSignInOptions 과 GoogleApiClient 를 생성한다.
private void doSomething() {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestProfile()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this) // 첫번째 this 는 FragmentActivity, 두번째 this 는 OnConnectionFailedListener
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
GoogleSignInOptions.Builder ref doc.
-
Sign in 은 아래 코드로 한다.
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
// 정보 가져오기
}
}
-
Sign out 은 아래 코드로 한다.
private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
// TODO
}
});
}
SignOut 전에는 반드시 GoogleApiClient 의 onConnected 가 불렸어야 한다.
-
앱과의 연결 끊기 (revoke)는 아래 코드로 한다.
private void revokeAccess() {
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
// [START_EXCLUDE]
updateUI(false);
// [END_EXCLUDE]
}
});
}
Revoke 전에는 반드시 GoogleApiClient 의 onConnected 가 불렸어야 한다.
-
GoogleSignInResult 로부터 정보를 가져오는 코드는 아래와 같다.
if (result.isSuccess()) {
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String personGivenName = acct.getGivenName();
String personFamilyName = acct.getFamilyName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
}
여기서 주의할 것은 email 주소는 바뀔 수 있기 때문에 getId 로 얻어온 id 값을 써야 한다.
-
이미 앱에 Signin 이 되어 있다면, SilentSignIn 을 통해 UI 없이 바로 로그인 시킬 수 있다.
SilentSignIn ref doc.
'프로그래밍 놀이터 > 안드로이드, Java' 카테고리의 다른 글
[android] App Shortcuts Tutorial (0) | 2018.02.25 |
---|---|
[android] Google Sign In 서버로 검증하기 #3 (0) | 2018.02.24 |
[android] Google Sign In 준비하기 #1 (2) | 2018.02.22 |
[android] odex 에 대해 알아보자. (0) | 2018.01.24 |
[android] earphone(headset) plug or unplug intent action (0) | 2018.01.22 |
댓글