'how to put FirebaseAuth.AuthStateListener on continous listening mode so that when the state changes, i get a notification

We have put the Firebase auth listener in a specific activity in the Android app. It only works when that activity occurs.

auth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        if (firebaseAuth.getCurrentUser() == null) {
            Log.i("firebase", "AuthState changed to null");
        }
        else {
            Log.i("firebase", "AuthState changed to "+firebaseAuth.getCurrentUser().getUid());
        }
    }
});

From what I understood, the firebase auth listener listens all the time and is triggered as soon as the firebase auth state changes. However, this does not seem to be the case in our case. Do we have to put this code in every activity or is there any way to put this in a single place and it lets us know as soon as the firebase authentication status changes?



Solution 1:[1]

You can get that code out of the activity and put it into a separate (repository) class. You can save the auth state into a LiveData object that can be observed in all your activities. According to the result, you can take some actions in your activity.

If you understand Kotlin, I have created an app for learning purposes where I have implemented this mechanism:

Another solution would be to have a single activity with several fragments. In this case, you need to attach the listener only once in the activity.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex Mamo