이번에는 구글 API를 이용하여 로그인 하는 앱을 만들 것이다.
https://firebase.google.com/docs/auth/android/google-signin?hl=ko#kotlin+ktx
전체 코드
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
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.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
public class MainActivity extends AppCompatActivity {
private static final int RC_SIGN_IN = 9001;
private GoogleSignInClient googleSignInClient;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
googleSignInClient = GoogleSignIn.getClient(this, gso);
mAuth = FirebaseAuth.getInstance();
SignInButton signInButton = findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(v -> signIn());
}
private void signIn() {
Intent signInIntent = googleSignInClient.getSignInIntent();
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) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
if (account != null) {
firebaseAuthWithGoogle(account.getIdToken());
}
} catch (ApiException e) {
Log.w("MainActivity", "Google sign in failed", e);
Toast.makeText(this, "Sign in failed: " + e.getStatusCode() + " - " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
private void firebaseAuthWithGoogle(String idToken) {
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
Log.w("MainActivity", "signInWithCredential:failure", task.getException());
Toast.makeText(this, "Sign in failed: " + task.getException().getMessage(), Toast.LENGTH_LONG).show();
updateUI(null);
}
});
}
private void updateUI(FirebaseUser user) {
if (user != null) {
Toast.makeText(this, "Signed in as: " + user.getEmail(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Sign in failed", Toast.LENGTH_SHORT).show();
}
}
}
strings.xml 파일에 안드로이드 클라이언트 id를 선언해줘야 한다.
<resources>
<string name="default_web_client_id">안드로이드 클라이언트 id</string>
</resources>
xml 코드
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.gms.common.SignInButton
android:id="@+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.917" />
</androidx.constraintlayout.widget.ConstraintLayout>
'소프트웨어 개발 > ANDROID_STUDIO' 카테고리의 다른 글
ANDROID STUDIO / 구글 로그인 후 구글 지도 생성 / 3 (0) | 2024.07.01 |
---|---|
ANDROID STUDIO / 애뮬레이터 인터넷 설정 (와이파이) 안될 때 해결방법 / 윈도우 11 (0) | 2024.07.01 |
구글 API 이용하는 법(안드로이드 기준) (0) | 2024.06.27 |
ANDROID STUDIO / 안드로이드 스튜디오 설치 / 1 (0) | 2024.06.25 |