如何解决AuthStateListener问题

时间:2019-03-22 21:06:25

标签: android firebase-authentication

我有两项活动: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();
            }
        }
    });
}

该如何解决?

1 个答案:

答案 0 :(得分:0)

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

这意味着您需要跟踪侦听器,所以:

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

通常在相反的生命周期事件中进行注册。根据您的情况,建议您将addAuthStateListener移到onStart上,然后使用

onStoponPause中注销它
mAuth.removeAuthStateListener(listener)