firebase 안드로이드 1 단계 - 설정 로그인 가입 기능
소스코드 다운로드
https://firebasestorage.googleapis.com/v0/b/testmemo-8978f.appspot.com/o/android_thanks_project%2FAndroid_Thanks1.zip?alt=media&token=f9cda798-6348-4bbd-8d89-d5e4c0af0f61
* 초기 설정
0. 안드로이드 플랫폼 설정해주기
1.Google-play.service.json을 app 수준에 넣어준다.
2.프로젝트 빌드 그래들 열어서 Sdk 추가하기
3.앱모듈안에도 sdk를 넣어준다.
4.싱크 나우 눌러주기
5.안되면 구글 리파지토리, sdk 업데이트
6.Apply plugin을 맨 아랫줄에 복사해서 넣어준다.
프로젝트 생성
구성파일 다운로드
프로젝트 수준 build.gradle
메니페스트
앱 수준 build.gradle
서명 인증서
서명인증서
--------------------------------------------------------------------------------------------------------------------------------------------------
join.activity
package me.happygate.thanks;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
import com.google.firebase.auth.FirebaseAuthWeakPasswordException;
import com.google.firebase.auth.FirebaseUser;
public class JoinActivity extends AppCompatActivity {
//이메일 비밀번호 로그인 모듈 변수
private FirebaseAuth mAuth;
//현재 로그인 된 유저 정보를 담을 변수
private FirebaseUser currentUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_join);
mAuth = FirebaseAuth.getInstance();
//이메일
final EditText emailTxt = (EditText)findViewById(R.id.emailTxt);
//이름
final EditText nameTxt = (EditText)findViewById(R.id.nameTxt);
//비밀번호
final EditText pwTxt = (EditText)findViewById(R.id.pwTxt);
//버튼
Button joinBtn = (Button)findViewById(R.id.joinBtn);
//버튼이 눌렀을 때
joinBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = emailTxt.getText().toString();
String name = nameTxt.getText().toString();
String pw = pwTxt.getText().toString();
Toast.makeText(JoinActivity.this,email +"/=가입 버튼 눌리고" + name +"/" + pw,Toast.LENGTH_SHORT).show();
//가입 성공했을 때 -> 감사리스트 메인 페이지로 이동하기
//Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
//startActivityForResult(signInIntent, 100);Toast.makeText(AuthActivity.this,"btn",Toast.LENGTH_SHORT).show();
//Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
// startActivityForResult(signInIntent, 100);
joinStart(email,name,pw);
}
});
}
//가입 함수
public void joinStart(String email, final String name, String password){
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(!task.isSuccessful()) {
try {
throw task.getException();
} catch(FirebaseAuthWeakPasswordException e) {
Toast.makeText(JoinActivity.this,"비밀번호가 간단해요.." ,Toast.LENGTH_SHORT).show();
} catch(FirebaseAuthInvalidCredentialsException e) {
Toast.makeText(JoinActivity.this,"email 형식에 맞지 않습니다." ,Toast.LENGTH_SHORT).show();
} catch(FirebaseAuthUserCollisionException e) {
Toast.makeText(JoinActivity.this,"이미존재하는 email 입니다." ,Toast.LENGTH_SHORT).show();
} catch(Exception e) {
Toast.makeText(JoinActivity.this,"다시 확인해주세요.." ,Toast.LENGTH_SHORT).show();
}
}else{
currentUser = mAuth.getCurrentUser();
Toast.makeText(JoinActivity.this, "가입 성공 " + name + currentUser.getEmail() + "/" + currentUser.getUid() ,Toast.LENGTH_SHORT).show();
startActivity(new Intent(JoinActivity.this, MainActivity.class));
finish();
}
}
});
}
}
login.activity
package me.happygate.thanks;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
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.FirebaseNetworkException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseAuthInvalidUserException;
import com.google.firebase.auth.FirebaseUser;
public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener{
//이메일 비밀번호 로그인 모듈 변수
private FirebaseAuth mAuth;
//현재 로그인 된 유저 정보를 담을 변수
private FirebaseUser currentUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance(); //이메일 비밀번호 로그인 모듈 변수
//이메일
final EditText emailTxt = (EditText)findViewById(R.id.emailTxt);
//비밀번호
final EditText pwTxt = (EditText)findViewById(R.id.pwTxt);
//버튼
Button joinBtn = (Button)findViewById(R.id.joinBtn);
//이메일
final TextView goJoinTxt = (TextView)findViewById(R.id.goJoinTxt);
//로그인 버튼이 눌렀을 때
joinBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = emailTxt.getText().toString();
String password = pwTxt.getText().toString();
//로그인 성공했을 때 -> 감사리스트 메인 페이지로 이동하기
loginStart(email, password);
}
});
//가입하러 가기 버튼 눌렀을 때
goJoinTxt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Toast.makeText(LoginActivity.this,"가입하러 가기 버튼 눌렀을 때",Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, JoinActivity.class));
finish();
}
});
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(LoginActivity.this,"연결이 해제되었습니다",Toast.LENGTH_SHORT).show();
}
//public Boolean check;
public void loginStart(String email, String password){
Toast.makeText(LoginActivity.this,"loginStart 함수 안으로" ,Toast.LENGTH_SHORT).show();
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Toast.makeText(LoginActivity.this,"mAuth. onComplete 함수" ,Toast.LENGTH_SHORT).show();
if (!task.isSuccessful()) {
try {
throw task.getException();
} catch (FirebaseAuthInvalidUserException e) {
Toast.makeText(LoginActivity.this,"존재하지 않는 id 입니다." ,Toast.LENGTH_SHORT).show();
} catch (FirebaseAuthInvalidCredentialsException e) {
Toast.makeText(LoginActivity.this,"이메일 형식이 맞지 않습니다." ,Toast.LENGTH_SHORT).show();
} catch (FirebaseNetworkException e) {
Toast.makeText(LoginActivity.this,"Firebase NetworkException" ,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(LoginActivity.this,"Exception" ,Toast.LENGTH_SHORT).show();
}
}else{
currentUser = mAuth.getCurrentUser();
Toast.makeText(LoginActivity.this, "로그인 성공" + "/" + currentUser.getEmail() + "/" + currentUser.getUid() ,Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}
});
}
//로그아웃 안했으면, 즉 로그인 되어있으면 자동으로 메인페이지로 이동시키기
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
currentUser = mAuth.getCurrentUser();
if(currentUser != null){
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}
}
Main.activity
package me.happygate.thanks;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity {
//이메일 비밀번호 로그인 모듈 변수
private FirebaseAuth mAuth;
//현재 로그인 된 유저 정보를 담을 변수
private FirebaseUser currentUser;
private TextView mTextMessage;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(currentUser.getEmail());
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(currentUser.getUid());
return true;
case R.id.navigation_notifications:
mTextMessage.setText(currentUser.getEmail());
return true;
}
return false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
//로그인 되어있으면 currentUser 변수에 유저정보 할당. 아닌경우 login 페이지로 이동!
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
currentUser = mAuth.getCurrentUser();
if(currentUser == null){
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
}
=============================================================================================================================
다음작업
1.가입할때 user name 파이어베이스 db에 push 시켜주기
2.로그아웃 기능
3.땡스피드 페이지 꾸미기 - tap layout , intent, viewpager 체크
*글쓰기 기능 - 저장 , null 체크
*조회 - 감사리스트 불러오기
*글 누르면 다른 user 프로필 페이지로 이동하기
'매일코딩 > firebase 안드로이드 테스트' 카테고리의 다른 글
firebase 안드로이드 2 단계 - tablayout framgment CustomAdapter 감사리스트 불러오기 (2) | 2018.02.19 |
---|
댓글