반응형
그래들
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
dependencies {
implementation platform('com.google.firebase:firebase-bom:26.2.0')
implementation 'com.google.android.gms:play-services-auth:19.0.0'
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.firebase:firebase-core:18.0.0'
implementation 'com.google.firebase:firebase-auth:20.0.1'
implementation 'com.firebaseui:firebase-ui-auth:7.1.1'
implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
여러 구글 설정을 거친 뒤, 파이어베이스 코어를 implements해준다.
// 메인 액티비티 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="276dp"
android:text="헬로우 월드"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.gms.common.SignInButton
android:layout_width="181dp"
android:layout_height="62dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2"
app:layout_constraintVertical_bias="0.182" />
</androidx.constraintlayout.widget.ConstraintLayout>
// 결과 액티비티 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="276dp"
android:text="헬로우 월드"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.gms.common.SignInButton
android:id="@+id/google_btn"
android:layout_width="181dp"
android:layout_height="62dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2"
app:layout_constraintVertical_bias="0.182" />
</androidx.constraintlayout.widget.ConstraintLayout>
//메인 엑티비티 java
package com.gohool.idontknow;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.GoogleAuthProvider;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
private SignInButton google_btn; //구글 로그인 버튼
private FirebaseAuth firebaseAuth; //파이어베이스 인증관련 객체
private GoogleApiClient googleApiClient;// 구글 API클라이언트 객체
private static final int REQ_SIGN_GOOGLE = 100; //구글 로그인 결과 코드
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//구글 signIn버튼 기본 옵션 정리(세팅)
GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
googleApiClient = new GoogleApiClient.Builder(this) //fragment라면 getContext로
.enableAutoManage(this,this)
.addApi(Auth.GOOGLE_SIGN_IN_API,googleSignInOptions)
.build();
firebaseAuth = FirebaseAuth.getInstance(); //파이어베이스 인증 객체 초기화
google_btn = findViewById(R.id.google_btn);
google_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient); //구글이 제공하는 intent 메소드
startActivityForResult(intent,REQ_SIGN_GOOGLE); //인증받고 다시 돌아옴
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { //구글 로그인 인증 요청시, 결과값 반환
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQ_SIGN_GOOGLE){
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if(result.isSuccess()){
GoogleSignInAccount account = result.getSignInAccount(); //사용자 정보 담고 있음
resultLogin(account); //로그인 결과값 출력 수행하라는 메소드
}
}
}
private void resultLogin(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
//최종적으로 로그인 성공 됐냐.
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "로그인 성공!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("nickname", account.getDisplayName()); //account안에 들어있는 이름가져오기
intent.putExtra("photoUrl",String.valueOf(account.getPhotoUrl())); //사진은 스트링으로 변환해줘야함
startActivity(intent);
}else {
Toast.makeText(MainActivity.this, "로그인 실패ㅠ", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
// 결과 액티비티 . java
package com.gohool.idontknow;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.bumptech.glide.Glide;
public class ResultActivity extends AppCompatActivity {
private TextView tv_result; //닉네임
private ImageView tv_profile; //이미지
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
Intent intent = getIntent();
String nickname = intent.getStringExtra("nickname"); //키값
String photoUrl = intent.getStringExtra("photoUrl");
tv_result = findViewById(R.id.textView);
tv_result.setText(nickname);
tv_profile = findViewById(R.id.ic_profile);
Glide.with(this).load(photoUrl).into(tv_profile);// 프로필 url을 이미지 뷰에 세팅.
}
}
1.파이어베이스에 인증은 됐지만, 결과 액티비티로 넘어가지 않았다.
문제는 textView의 id값을 넘겼어야했는데, Layout의 id를 넘겨주고있었다. 어쩐지.. .ㅠ
파이어베이스 인증과 + 로그인 회원 가입 만들기
반응형
'개발언어 > JAVA' 카테고리의 다른 글
클래스와 인스턴스 그리고 객체 (0) | 2020.12.31 |
---|---|
안드로이드 로그인+회원가입+구글로그인 (0) | 2020.12.30 |
데이터베이스 MySQL (0) | 2020.12.28 |
안드로이드 로그인 + 회원가입 만들기 (0) | 2020.12.27 |
안드로이드 하단 메뉴만들기 (0) | 2020.12.26 |