BÀI 33 - ĐĂNG NHẬP BẰNG TÀI KHOẢN GOOGLE TRONG LẬP TRÌNH ANDROID

Video bài học:

Đầu tiên phải nạp khóa SHA-1 và SHA-256 cho Firebase. (Vào Gradle {góc phải màn hình} > Task > Android > signingReport để lấy 2 khóa này)

Sau đó download file .json và nạp về ứng dung (Projects > App)

Rồi mới code theo đoạn code bên dưới (nếu chưa hiểu code có thể tham khảo video bên trên. Nhưng video bên trên tác giả dùng ngôn ngữ Kotin chứ không phải java nên bạn có thể tham khảo hoặc tìm video khác phù hợp với bạn hơn).

private static final int RC_SIGN_IN = 123;

private GoogleSignInClient mGoogleSignInClient;

private FirebaseAuth mAuth;


@Override

protected void onStart() {

super.onStart();


FirebaseUser user = mAuth.getCurrentUser();

if (user!=null) {

Intent intent = new Intent(getApplicationContext(), ManHinhChuyenDen.class);

startActivity(intent);

}

}


@Override

protected void onCreate(Bundle savedInstanceState) {

mAuth = FirebaseAuth.getInstance();

DangNhapGoogle();


button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

signIn();

}

});

}


private void signIn() {

Intent signInIntent = mGoogleSignInClient.getSignInIntent();

startActivityForResult(signInIntent, RC_SIGN_IN);

}


private void DangNhapGoogle() {


GoogleSignInOptions gso = new GoogleSignInOptions

.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)

.requestIdToken(getString(R.string.default_web_client_id))

.requestEmail()

.build();


mGoogleSignInClient = GoogleSignIn.getClient(this, gso);


}


@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);

firebaseAuthWithGoogle(account);

} catch (ApiException e) {

Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();

}

}

}


private void firebaseAuthWithGoogle(GoogleSignInAccount account) {

AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);

mAuth.signInWithCredential(credential)

.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {

@Override

public void onComplete(@NonNull Task<AuthResult> task) {

if (task.isSuccessful()) {

FirebaseUser user = mAuth.getCurrentUser();

Intent intent = new Intent(getApplicationContext(), ManHinhChuyenDen.class);

startActivity(intent);


} else {

Toast.makeText(ManHinhHienTai.this, "Auth failed", Toast.LENGTH_SHORT).show();

}

}

});

}


Xong phần trên thì firebase sẽ cập nhật tài khoản ngay lập tức và bạn có thể truy suất tài khoản này theo id được firebase cung cấp

Code ManHinhChuyenDen

TextView tv1, tv2;

@Override

protected void onCreate(Bundle savedInstanceState) {

tv1 = findViewById(R.id.textView2);

tv2 = findViewById(R.id.textView3);

btnDangSuat = findViewById(R.id.button);



GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);

if (signInAccount!=null) {

tv1.setText(signInAccount.getDisplayName());

tv2.setText(signInAccount.getEmail());

}


btnDangSuat.setOnClickListener(v -> {

FirebaseAuth.getInstance().signOut();

Intent intent = new Intent(getApplicationContext(), ManHinhHienTai.class);

startActivity(intent);

});


}

Fix lỗi code:10 khi đăng nhập tài khoản Google (này là khi code xong hết rồi. Khi bấm vào sign in with Google và chọn tài khoản rồi thì nó lại báo lỗi ":10") mình đã gặp lỗi này từ lúc chạy máy ảo, sửa được trên máy ảo thì khi xuất file apk nó lại lỗi trên file apk và mất rất nhiều thời gian để tìm kiếm sửa lỗi này. Dưới đây là cách mình đã fix thành công.

  • Theo mình nhọc nhàng tìm hiểu suốt 1 ngày 1 đêm thì lỗi này thường là do khóa SHA-1 do android studio tạo ra để xác minh bị thay đổi. Bạn phải tìm đến trình tạo mã này (Gradle >> tasks >> android >> signingReport) để cập nhật khóa lại cho Firebase.

  • Và một cách fix khác nếu ở trên không được thì bạn phải thêm vào đoạn code này vào buil.grade. Vì có thể app bị trùng lặp khóa gì đó nên không tìm thấy điều nó cần tìm.

android {

signingConfigs {

debug {

storeFile file("your path to keystore file")

storePassword "keystorepass123"

keyAlias "youralias"

keyPassword "yourkeypass"

}

}

...

  • Thực chất thì đây là những key để Google play xác minh app của bạn (bạn phải tạo chúng bằng cách build file apk), cũng như để bảo mật cho app của tránh bị hacker tấn công và sửa đổi app. Nên bạn phải giữ tuyệt đối bí mật và dễ nhớ nhé. Mình tham khảo từ video này nè: youtube