android - 如何解决此 AuthStateListener 问题
问题描述
我有两个活动:SignIn
和SignUp
。他们每个人都有一个 AuthStateListener。
SignIn
问题是当应用程序处于SignUp
活动状态并且身份验证状态发生更改时,来自活动的 AuthStateListener被调用(当我登录两个侦听器时发现这个)。
SignIn 的 onCreate 方法:
@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 方法:
@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
再被调用,则需要通过调用取消注册removeAuthStateListener
。
这意味着您需要跟踪侦听器,因此:
listener = new FirebaseAuth.AuthStateListener() {
...
}
mAuth.addAuthStateListener(listener);
您通常会在注册它们的相反生命周期事件中执行此操作。在您的情况下,我建议您继续使用addAuthStateListener
,onStart
然后将其注销或onStop
注销onPause
mAuth.removeAuthStateListener(listener)
推荐阅读
- python - GridSearchCV 最佳超参数不会产生最佳精度
- python - 需要帮助将 ibkr api 发送到 50msg/min
- java - 蓝牙 LE 扫描仪没有结果
- laravel-backpack - 小屏幕上的过滤器折叠问题
- java - 为什么android studio在初始化Buttons、EditText和SwitchCompats时会出现NullPointerException?
- visual-studio-code - Visual Studio Code:如何使用 F4 重复上次操作
- python - Python Closure 可以存储和更改外部标量吗?
- amazon-web-services - EC2 Linux 端口 7070 上的 Dotnet 应用程序无法访问
- c++ - 在 C++ 中执行多元线性回归
- java - 在java中的特定字符之后替换特定单词