Is it necessary to add an AuthStateListener in every activity of Android Firebase?

Imran Anwar Source

Is it necessary to add an AuthStateListener in every activity of Android Firebase? I have added AuthStateListener in login activity.I want to know that is it enough?



answered 6 months ago Levi Moreira #1

It really depends on what you want to monitor. According to the docs you'll use this listener to listen to events on:

  • Right after the listener has been registered
  • When a user is signed in
  • When the current user is signed out
  • When the current user changes

In the activities you need to know those things you should register the listener. But in my experience you'll need register it only in the login activity.

answered 6 months ago shadowsheep #2

I don't think it's necessary. You need to have it in the activity that have to to the sign-in environment setup, or sign out environment clenup in a way like that:

mAuthStateListener = new FirebaseAuth.AuthStateListener() {
            public void onAuthStateChanged(@NonNull final FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();

                if (null != user) {
                } else {

This is usually done by the activity that manage the sign-in process either through FirebaseUI or with the only SDK API.

Remember to do the user reload() in the signin init function so that to manage situations like the case you have deleted a user from the console, the application didn't know that because of caching:

private void onSignedInInitialize(FirebaseUser user) {
        if (null != user) {

You need to have a listener in all the other Activities where you need to respond to events related to the user sign-in, sign-out or updates.

In all other activities all you have to check is only if the user is not null.

if (null != user) { 

Where user is the user taken from the the FirebaseAuth instance

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

Usually where you use the listener you create it in the onCreate activity method and you add it in the onResume and remove it in the onPause

    protected void onResume() {
        if (null != mAuthStateListener) {

    protected void onPause() {
        if (null != mAuthStateListener) {

comments powered by Disqus