首页 > 解决方案 > 如何解决此 AuthStateListener 问题

问题描述

我有两个活动:SignInSignUp。他们每个人都有一个 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();
            }
        }
    });
}

可以做些什么来解决这个问题?

标签: androidfirebase-authentication

解决方案


如果您不想AuthStateListener再被调用,则需要通过调用取消注册removeAuthStateListener

这意味着您需要跟踪侦听器,因此:

listener = new FirebaseAuth.AuthStateListener() {
  ...
}
mAuth.addAuthStateListener(listener);

您通常会在注册它们的相反生命周期事件中执行此操作。在您的情况下,我建议您继续使用addAuthStateListeneronStart然后将其注销或onStop注销onPause

mAuth.removeAuthStateListener(listener)

推荐阅读