我仍在學習 Firebase。我使用 Firebase 身份驗證創建了一個登錄程式。在使 LoginActivity 和 HomeActivity 程式順利運行時,當我按下回傳按鈕然后再次打開應用程式時,要求用戶重新登錄。如何讓用戶不被要求重新登錄?
我試圖在 stackoverflow 和 YouTube 上的幾個頻道上找到相同問題的解決方案,但沒有找到答案。我真的很感激任何答案,如果我的英語很亂,我很抱歉。
這是 LoginActivity 的代碼片段。
FirebaseAuth mAuth = FirebaseAuth.getInstance();
SharedPreferences sharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()){
Toast.makeText(LoginActivity.this, "Login succes !", Toast.LENGTH_SHORT).show();
user = mAuth.getCurrentUser();
updateUI(user);
}else{
Toast.makeText(LoginActivity.this, "Login Gagal !", Toast.LENGTH_SHORT).show();
}
}
});
private void updateUI(FirebaseUser user) {
if (user != null){
String id = user.getUid();
String userEmail = user.getEmail();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("firebaseKey", id);
editor.commit();
gotoHomeActivity();
}
}
private void gotoHomeActivity() {
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
這是來自 HomeActivity 的代碼片段。
FirebaseAuth mAuth = FirebaseAuth.getInstance();
SharedPreferences sharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
String uid = sharedPreferences.getString("firebaseKey", "");
uj5u.com熱心網友回復:
一旦您的用戶登錄后,他們在使用 FirebaseAuth 時通常不需要再次登錄。問題可能是您每次都在呼叫“登錄”例程。
相反,您應該首先在登錄螢屏上添加一個身份驗證狀態偵聽器,當您收到回應時,您可以轉到主螢屏(如果他們已經登錄)或啟動登錄程序。
mAuth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull final FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
// already logged in, go to home screen
}
else {
// initiate sign-in
}
}
}
);
請注意,一旦您注冊了偵聽器,就會立即呼叫該偵聽器,有時還會在此后不久再次呼叫該偵聽器。如果這最終成為一個問題,那么在鏈接的問題上有一些解決方案。
Kotlin 版本
auth.addAuthStateListener(AuthStateListener { firebaseAuth ->
if( firebaseAuth.currentUser != null ) {
// user is already logged in, go to home screen
}
else {
// initiate sign in
}
})
uj5u.com熱心網友回復:
在您的 LoginActivity 中,檢查用戶是否已經登錄 -
if(mAuth.getCurrentUser()!=null){
// if true open MainActivity
Intent intent = new Intent(SignupActivity.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); // to stop flashing of activity when intent is working
startActivity(intent);
finish();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/408719.html
標籤:
