728x90
반응형
SMALL
Google API
Google API는 구글 로그인 연동 기능을 제공하고 있다.
Google API 프로젝트 구성
인증 사이트에서 OAuth 2.0 웹 클라이언트 ID를 지정해야 한다. 실제 앱에서는 이 클라이언트 ID가 앱의 백엔드 서버를 나타낸다.
앱 등록 및 설정
Google API Console에 프로젝트를 만들고 SHA 인증서 지문을 등록하면 된다.
Gradle 서명 보고서
gradle task에서 gradle signingreport를 입력한다.
인증서 지문을 등록하면 구글 로그인을 위한 OAuth client가 구성된다.
build.gradle
dependencies {
/* ... */
implementation 'com.google.android.gms:play-services-auth:20.3.0'
/* ... */
}
themes.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
<!-- Activity with no Title -->
<style name="ThemeOverlay.MyNoTitleActivity" parent="AppTheme">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<!-- Dark Buttons -->
<style name="ThemeOverlay.MyDarkButton" parent="ThemeOverlay.AppCompat.Dark">
<item name="colorButtonNormal">@color/blue_grey_500</item>
<item name="android:textColor">@android:color/white</item>
</style>
</resources>
string.xml
<resources>
<string name="app_name">Sign-In Quickstart</string>
<string name="title_text">Google Sign-In\nQuickstart</string>
<!-- Sign-in status messages -->
<string name="signed_in_fmt">Signed in as: %s</string>
<string name="signed_in">Signed in</string>
<string name="signing_in">Signing in…</string>
<string name="signed_out">Signed out</string>
<string name="signed_in_err">"Error: please check logs."</string>
<string name="error_null_person">
Error: Plus.PeopleApi.getCurrentPerson returned null. Ensure that the Google+ API is
enabled for your project, you have a properly configured google-services.json file
and that your device has an internet connection.
</string>
<string name="loading">Loading…</string>
<string name="auth_code_fmt">Auth Code: %s</string>
<string name="id_token_fmt">ID Token: %s</string>
<!-- Google Play Services error for Toast -->
<string name="play_services_error_fmt">Google Play Services Error: %i</string>
<!-- Button labels -->
<string name="sign_out">Sign Out</string>
<string name="disconnect">Disconnect</string>
<string name="refresh_token">Get Fresh Token</string>
<!-- Content Description for images -->
<string name="desc_google_icon">Google Logo</string>
<!-- Rationale for asking for Contacts -->
<string name="contacts_permission_rationale">Contacts access is needed in order to retrieve your email address.</string>
<!-- Activity Names and Descriptions -->
<string name="name_sign_in_activity">SignInActivity</string>
<string name="desc_sign_in_activity">Signing in, signing out, and revoking access.</string>
<string name="desc_sign_in_activity_scopes">Signing in, signing out, and revoking access with Google Drive permissions.</string>
<string name="name_id_token_activity">IdTokenActivity</string>
<string name="desc_id_token_activity">Retrieving an ID Token for the user.</string>
<string name="desc_auth_code_activity">Demonstrate retrieving an auth code for authorizing your server.</string>
<string name="name_auth_code_activity">ServerAuthCodeActivity</string>
<string name="desc_rest_activity">Demonstrate using Google Sign In with a Google REST API</string>
<string name="name_rest_activity">RestApiActivity</string>
<!-- Messages for the Rest API activity -->
<string name="connections_fmt">Connections: %1$s</string>
<string name="msg_contacts_failed">Get contacts failed.</string>
<!-- TODO(user): replace with your real server client ID -->
<!-- Server Client ID. This should be a valid Web OAuth 2.0 Client ID obtained
from https://console.developers.google.com/ -->
<string name="server_client_id">YOUR_SERVER_CLIENT_ID</string>
</resources>
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="blue_grey_500">#607D8B</color>
<color name="blue_grey_600">#546E7A</color>
<color name="blue_grey_700">#455A64</color>
<color name="blue_grey_800">#37474F</color>
<color name="blue_grey_900">#263238</color>
</resources>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/blue_grey_700"
android:orientation="vertical"
android:weightSum="4"
tools:context=".SignInActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:id="@+id/google_icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="@dimen/g_top_margin"
android:contentDescription="@string/desc_google_icon"
android:src="@drawable/googleg_color" />
<TextView
android:id="@+id/title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="@string/title_text"
android:gravity="center"
android:textColor="@android:color/white"
android:textSize="36sp" />
<TextView
android:id="@+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/signed_out"
android:textColor="@android:color/white"
android:textSize="14sp" />
<TextView
android:id="@+id/detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fadeScrollbars="true"
android:gravity="center"
android:maxLines="5"
android:padding="10dp"
android:scrollbars="vertical"
android:textColor="@android:color/white"
android:textSize="14sp" />
<Button
android:id="@+id/button_optional_action"
style="@style/Base.Widget.AppCompat.Button.Borderless.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
tools:text="Optional Action"
tools:visibility="visible" />
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@color/blue_grey_900">
<com.google.android.gms.common.SignInButton
android:id="@+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"
tools:visibility="gone" />
<LinearLayout
android:id="@+id/sign_out_and_disconnect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:visibility="gone"
tools:visibility="visible">
<Button
android:id="@+id/sign_out_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/sign_out"
android:theme="@style/ThemeOverlay.MyDarkButton" />
<Button
android:id="@+id/disconnect_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/disconnect"
android:theme="@style/ThemeOverlay.MyDarkButton" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
java
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
/**
* Activity to demonstrate basic retrieval of the Google user's ID, email address, and basic
* profile.
*/
public class SignInActivity extends AppCompatActivity implements
View.OnClickListener {
private static final String TAG = "SignInActivity";
private static final int RC_SIGN_IN = 9001;
private GoogleSignInClient mGoogleSignInClient;
private TextView mStatusTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Views
mStatusTextView = findViewById(R.id.status);
// Button listeners
findViewById(R.id.sign_in_button).setOnClickListener(this);
findViewById(R.id.sign_out_button).setOnClickListener(this);
findViewById(R.id.disconnect_button).setOnClickListener(this);
// [START configure_signin]
// 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();
// [END configure_signin]
// [START build_client]
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
// [END build_client]
// [START customize_button]
// Set the dimensions of the sign-in button.
SignInButton signInButton = findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_STANDARD);
signInButton.setColorScheme(SignInButton.COLOR_LIGHT);
// [END customize_button]
}
@Override
public void onStart() {
super.onStart();
// [START on_start_sign_in]
// 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);
// [END on_start_sign_in]
}
// [START 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);
}
}
// [END onActivityResult]
// [START handleSignInResult]
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);
}
}
// [END handleSignInResult]
// [START signIn]
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
// [END signIn]
// [START signOut]
private void signOut() {
mGoogleSignInClient.signOut()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
// [START_EXCLUDE]
updateUI(null);
// [END_EXCLUDE]
}
});
}
// [END signOut]
// [START revokeAccess]
private void revokeAccess() {
mGoogleSignInClient.revokeAccess()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
// [START_EXCLUDE]
updateUI(null);
// [END_EXCLUDE]
}
});
}
// [END revokeAccess]
private void updateUI(@Nullable GoogleSignInAccount account) {
if (account != null) {
mStatusTextView.setText(getString(R.string.signed_in_fmt, account.getDisplayName()));
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
} else {
mStatusTextView.setText(R.string.signed_out);
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
case R.id.sign_out_button:
signOut();
break;
case R.id.disconnect_button:
revokeAccess();
break;
}
}
}
https://github.com/googlesamples/google-services
728x90
반응형
LIST
'App Programming > Android Studio' 카테고리의 다른 글
[Android Studio] 공유하기 기능 (Android Sharesheet) (0) | 2022.12.22 |
---|---|
[Android Studio] 카메라 API (0) | 2022.12.09 |
[Android Studio] 하이퍼링크 (Hyperlink) (0) | 2022.11.25 |
[Android Studio] 버튼 클릭시 버튼 색상 변경 (0) | 2022.11.21 |
[Android Studio] 하단 네비게이션 (Bottom Navigation) (0) | 2022.11.18 |