How do I fix this AuthStateListener issue

依然范特西╮ 提交于 2019-12-23 05:47:11

问题


I have two activities: SignIn and SignUp. Each of them has an 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).

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();
                    }
                });
            }
        }
    });

   ........
}

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();
            }
        }
    });
}

What can be done to fix this?


回答1:


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);

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)


来源:https://stackoverflow.com/questions/55307773/how-do-i-fix-this-authstatelistener-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!