如何解决AuthStateListener问题 [英] How do I fix this AuthStateListener issue
问题描述
我有两个活动:SignIn
和SignUp
.他们每个人都有一个AuthStateListener.
I have two activities: SignIn
and SignUp
. Each of them has an AuthStateListener.
问题在于,当应用程序处于SignUp
活动中并且身份验证状态发生更改时,SignIn
活动中的AuthStateListener会被调用(当我登录两个侦听器时都发现了此问题).
The problem is that AuthStateListener from SignIn
activity gets called when app is in SignUp
activity and authentication state is changed (Found this when I logged in both listener).
SignIn的onCreate方法:
onCreate method of SignIn :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
mAuth = FirebaseAuth.getInstance();
mAuth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
progressBar.setVisibility(View.INVISIBLE);
if (mAuth.getCurrentUser() != null && isEmailVerified()) {
Toast.makeText(SignIn.this, "Signed In", Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(SignIn.this, UserProfile.class));
} else if (mAuth.getCurrentUser() != null) {
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast.makeText(SignIn.this, "Verification email sent You can sign in once your account is verified.", Toast.LENGTH_SHORT).show();
mAuth.signOut();
}
});
}
}
});
........
}
SignUp的onCreate方法:
onCreate method of SignUp :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
mAuth = FirebaseAuth.getInstance();
.....
mAuth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if (mAuth.getCurrentUser() != null) {
verifyEmail();
}
}
});
}
该如何解决?
推荐答案
如果您不想再调用AuthStateListener
,则需要通过调用
If you don't want an AuthStateListener
to be called anymore, you need to unregister it by calling removeAuthStateListener
.
这意味着您需要跟踪侦听器,所以:
This means you need to keep track of the listener, so:
listener = new FirebaseAuth.AuthStateListener() {
...
}
mAuth.addAuthStateListener(listener);
通常会在与注册它们相反的生命周期事件中执行此操作.对于您的情况,我建议将addAuthStateListener
移到onStart
上,然后使用
在onStop
或onPause
中注销它.
You'd typically do that in the opposite lifecycle event of where you register them. In your case I'd recommend moving the addAuthStateListener
on onStart
and then unregister it in onStop
or in onPause
with
mAuth.removeAuthStateListener(listener)
这篇关于如何解决AuthStateListener问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!