AndroidアプリでGoogle認証

AndroidアプリからGoogle認証を使う。
ユーザーがボタンを押したらGoogleで認証を行い、Googleからメールアドレスなどを取得する。

OAuth クライアント ID を作成

Google APIs コンソール にアクセスしOAuth クライアント ID を作成する。

実装

build.gradle(モジュール)

dependencies {
    ・・・
    implementation 'com.google.android.gms:play-services-auth:16.0.1'
}

layout.xml

公式から、com.google.android.gms.common.SignInButtonも提供されているが、デザインを合わせたいので独自のボタンを使用する。

    <com.beardedhen.androidbootstrap.BootstrapButton
        android:id="@+id/login_google"
        app:bootstrapText="Google でログイン"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginTop="24dp"
        app:bootstrapBrand="primary"
        app:bootstrapSize="lg"
        app:buttonMode="regular"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/xxxx"
        app:showOutline="false" />

Activity

public class XxxxActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
    ・・・
    static final int RC_SIGN_IN_GOOGLE = 999;
    BootstrapButton btnLoginGoogle;
    GoogleApiClient googleApiClient;
    ・・・
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ・・・
        GoogleSignInOptions gso = new GoogleSignInOptions
                .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();
        googleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this , this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
        btnLoginGoogle = findViewById(R.id.login_google);
        btnLoginGoogle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
                startActivityForResult(signInIntent, RC_SIGN_IN_GOOGLE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN_GOOGLE) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                GoogleSignInAccount googleSignInAccount = result.getSignInAccount();
                doSomesthing(
                        googleSignInAccount.getId(),
                        googleSignInAccount.getEmail(),
                        googleSignInAccount.getDisplayName());
            }
        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        // to do
    }

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

CAPTCHA