[Android]Firebase登録、ログイン、匿名ログイン


1.基本登録プロバイダをパイに追加



2.Firebase認証ライブラリレベルに追加


implementation 'com.google.firebase:firebase-auth-ktx'

3.FurebaseAuthインスタンスの宣言と初期化

// FirebaseAuth 의 인스턴스를 선언합니다.
private lateinit var auth: FirebaseAuth
// onCreate() 메서드에서 FirebaseAuth 인스턴스를 초기화합니다. 
auth = Firebase.auth

4.新規加入

// createUserWithEmailAndPassword 메서드를 사용하여 이메일 주소와 비밀번호를 가져와 유효성을 검사
auth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                // Sign in success, update UI with the signed-in user's information
                Toast.makeText(this, "성공", Toast.LENGTH_LONG).show()
            } else {
                // If sign in fails, display a message to the user.
                Toast.makeText(this, "실패", Toast.LENGTH_LONG).show()
            }
        }

5.既存ユーザーへのログイン

// signInWithEmailAndPassword 메서드를 사용하여 이메일 주소와 비밀번호를 가져와 유효성을 검사한 후 사용자를 로그인
auth.signInWithEmailAndPassword(email, password)
    	.addOnCompleteListener(this) { task ->
        	if (task.isSuccessful) {
            	// Sign in success, update UI with the signed-in user's information
                Toast.makeText(this, "로그인 성공", Toast.LENGTH_LONG).show()
            } else {
             	// If sign in fails, display a message to the user.
                Toast.makeText(this, "로그인 실패", Toast.LENGTH_LONG).show()
            } 
        }

6.ログアウト

auth.signOut()

7.匿名認証

// signInAnonymously를 호출하여 익명 사용자로 로그인
auth.signInAnonymously()
		.addOnCompleteListener(this) { task ->
        	if (task.isSuccessful) {
            	// Sign in success, update UI with the signed-in user's information
                Toast.makeText(this, "익명 인증 성공", Toast.LENGTH_LONG).show()
            } else {
              	// If sign in fails, display a message to the user.
              	Toast.makeText(this, "익명 인증 실패", Toast.LENGTH_LONG).show()
            }
        }

8.すべてのソース


- activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout>
    <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">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:gravity="center">
            <Button
                android:id="@+id/loginBtn"
                android:layout_width="300dp"
                android:layout_height="50dp"
                android:layout_margin="5dp"
                android:background="@drawable/background_radius"
                android:text="로그인"
                android:textSize="14sp"
                android:textStyle="bold"/>
            <Button
                android:id="@+id/joinBtn"
                android:layout_width="300dp"
                android:layout_height="50dp"
                android:layout_margin="5dp"
                android:background="@drawable/background_radius"
                android:text="회원가입"
                android:textSize="14sp"
                android:textStyle="bold"/>
            <Button
                android:id="@+id/noAccountBtn"
                android:layout_width="300dp"
                android:layout_height="50dp"
                android:layout_margin="5dp"
                android:background="@drawable/background_radius"
                android:text="비회원 가입"
                android:textSize="14sp"
                android:textStyle="bold"/>
        </LinearLayout>
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

- activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<layout>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center"
        tools:context=".LoginActivity">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:gravity="center"
                android:text="로그인"
                android:textColor="@color/black"
                android:textSize="20sp"
                android:textStyle="bold" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:orientation="vertical">
            <EditText
                android:id="@+id/emailArea"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:hint="email"
                android:background="@android:color/transparent"
                android:textSize="15sp"
                android:layout_margin="10dp"/>
            <EditText
                android:id="@+id/passwordArea"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:hint="password"
                android:inputType="textPassword"
                android:background="@android:color/transparent"
                android:textSize="15sp"
                android:layout_margin="10dp"/>
            <Button
                android:id="@+id/loginBtn"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:text="로그인"
                android:layout_margin="20dp" />
        </LinearLayout>
    </LinearLayout>
</layout>

- activity_join.xml

<?xml version="1.0" encoding="utf-8"?>
<layout>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center"
        tools:context=".JoinActivity">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:gravity="center"
                android:text="회원가입"
                android:textColor="@color/black"
                android:textSize="20sp"
                android:textStyle="bold" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:orientation="vertical">
            <EditText
                android:id="@+id/emailArea"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:hint="email"
                android:background="@android:color/transparent"
                android:textSize="15sp"
                android:layout_margin="10dp"/>
            <EditText
                android:id="@+id/passwordArea"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:hint="password"
                android:inputType="textPassword"
                android:background="@android:color/transparent"
                android:textSize="15sp"
                android:layout_margin="10dp"/>
            <EditText
                android:id="@+id/chekPasswordArea"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:hint="password check"
                android:inputType="textPassword"
                android:background="@android:color/transparent"
                android:textSize="15sp"
                android:layout_margin="10dp"/>
            <Button
                android:id="@+id/loginBtn"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:text="회원가입"
                android:layout_margin="20dp" />
        </LinearLayout>
    </LinearLayout>
</layout>

- MainActivity.kt

class MainActivity : AppCompatActivity() {
    private lateinit var auth: FirebaseAuth
    private lateinit var binding : ActivityIntroBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        auth = Firebase.auth
        binding = DataBindingUtil.setContentView(this, R.layout.activity_intro)
        binding.loginBtn.setOnClickListener {
            val intent = Intent(this, LoginActivity::class.java)
            startActivity(intent)
        }
        binding.joinBtn.setOnClickListener {
            val intent = Intent(this, JoinActivity::class.java)
            startActivity(intent)
        }
        binding.noAccountBtn.setOnClickListener {
            auth.signInAnonymously()
                .addOnCompleteListener(this) { task ->
                    if (task.isSuccessful) {
                        // Sign in success, update UI with the signed-in user's information
                        Toast.makeText(this, "비회원 로그인 성공", Toast.LENGTH_LONG).show()
                    } else {
                        // If sign in fails, display a message to the user.
                        Toast.makeText(this, "비회원 로그인 실패", Toast.LENGTH_LONG).show()
                    }
                }
        }
    }
}

- LoginActivity.kt

class LoginActivity : AppCompatActivity() {
    private lateinit var auth: FirebaseAuth
    private lateinit var binding: ActivityLoginBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        auth = Firebase.auth
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login)
        binding.loginBtn.setOnClickListener {
            val email = binding.emailArea.text.toString()
            val password = binding.passwordArea.text.toString()
            auth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this) { task ->
                    if (task.isSuccessful) {
                        // Sign in success, update UI with the signed-in user's information
                        Toast.makeText(this, "로그인 성공", Toast.LENGTH_LONG).show()
                    } else {
                        // If sign in fails, display a message to the user.
                        Toast.makeText(this, "로그인 실패", Toast.LENGTH_LONG).show()
                    }
                }
        }
    }
}

- JoinActivity.kt

class JoinActivity : AppCompatActivity() {
    private lateinit var auth: FirebaseAuth
    private lateinit var binding: ActivityJoinBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        auth = Firebase.auth
        binding = DataBindingUtil.setContentView(this, R.layout.activity_join)
        binding.joinBtn.setOnClickListener {
            var isGoToJoin = true
            val email = binding.emailArea.text.toString()
            val password = binding.passwordArea1.text.toString()
            val passwordCheck = binding.chekPasswordArea.text.toString()
            if (email.isEmpty()) {
                Toast.makeText(this, "이메일을 입력해주세요.", Toast.LENGTH_LONG).show()
                isGoToJoin = false
            }
            if (password.isEmpty()) {
                Toast.makeText(this, "password1을 입력해주세요.", Toast.LENGTH_LONG).show()
                isGoToJoin = false
            }
            if (passwordCheck.isEmpty()) {
                Toast.makeText(this, "password2을 입력해주세요.", Toast.LENGTH_LONG).show()
                isGoToJoin = false
            }
            if (password != passwordCheck) {
                Toast.makeText(this, "비밀번호를 똑같이 입력해주세요.", Toast.LENGTH_LONG).show()
                isGoToJoin = false
            }
            if (password.length < 6) {
                Toast.makeText(this, "비밀번호를 6자리 이상으로 입략헤주세요.", Toast.LENGTH_LONG).show()
                isGoToJoin = false
            }
            if (isGoToJoin) {
                auth.createUserWithEmailAndPassword(email, password)
                    .addOnCompleteListener(this) { task ->
                        if (task.isSuccessful) {
                            // Sign in success, update UI with the signed-in user's information
                            Toast.makeText(this, "화원가입 성공", Toast.LENGTH_LONG).show()
                        } else {
                            // If sign in fails, display a message to the user.
                            Toast.makeText(this, "회원가입 실패", Toast.LENGTH_LONG).show()
                        }
                    }
            }
        }
    }
}