BÀI 46 - XÁC THỰC ĐĂNG NHẬP BẰNG TÀI KHOẢN EMAIL TRONG LẬP TRÌNH ANDROID

  • Đầu tiên, cũng phải thêm các thư viện của Firebase vào ứng dụng:

  • Trong tệp Gradle cấp gốc (cấp dự án) của bạn ( build.gradle ), hãy thêm các quy tắc để bao gồm plugin Gradle Dịch vụ của Google.

buildscript {

repositories {

// Check that you have the following line (if not, add it):

google() // Google's Maven repository

}

dependencies {

// Add the following line:

classpath 'com.google.gms:google-services:4.3.8' // Google Services plugin

}

}

  • Trong tệp Gradle mô-đun (cấp ứng dụng) của bạn (thường là app/build.gradle ), hãy áp dụng plugin Gradle Dịch vụ của Google:

apply plugin: 'com.android.application'

// Add the following line:

apply plugin: 'com.google.gms.google-services' // Google Services plugin

  • Thêm SDK Firebase vào ứng dụng của bạn. Khai báo chúng trong tệp Gradle mô-đun (cấp ứng dụng) của bạn (thường là app/build.gradle ).

dependencies {

implementation platform('com.google.firebase:firebase-bom:28.2.1')

implementation 'com.google.firebase:firebase-analytics'

// Declare the dependencies for any other desired Firebase products

// For example, declare the dependencies for Firebase Authentication and Cloud Firestore

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

}

public FirebaseAuth mAuth;

public FirebaseUser user;


@Override

public void onStart() {

super.onStart();

mAuth.addAuthStateListener(authStateListener);

}


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

mAuth.createUserWithEmailAndPassword(lienLac, matKhau).addOnCompleteListener(task -> {

if (task.isSuccessful()) {

sendVerificationEmail();

} else {

if (user.isEmailVerified()) {

// Email đã xác minh

} else if (task.getException() instanceof FirebaseAuthUserCollisionException) {

// Email đã tồn tại

}

}

});


}


private void sendVerificationEmail() {

user = mAuth.getCurrentUser();

assert user != null;

user.sendEmailVerification()

.addOnSuccessListener(unused ->

Toast.makeText(this, "Kiểm tra email của bạn",

Toast.LENGTH_SHORT).show())

.addOnFailureListener(e ->

Toast.makeText(this, "Không tìm thấy email của bạn",

Toast.LENGTH_SHORT).show());

}

}

Kiểm tra đăng nhập

private FirebaseAuth mAuth;

mAuth = FirebaseAuth.getInstance();

FirebaseUser user = mAuth.getCurrentUser();

if (user != null) {

Đã đăng nhập

}