Is it necessary to add an AuthStateListener in eve

2020-06-24 06:16发布

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?

2条回答
在下西门庆
2楼-- · 2020-06-24 06:50

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() {
            @Override
            public void onAuthStateChanged(@NonNull final FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();

                if (null != user) {
                    onSignedInInitialize(user);
                } else {
                    onSignedOutCleanup();
                }
            }
        };

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) {
        user.reload();
        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

    @Override
    protected void onResume() {
        super.onResume();
        if (null != mAuthStateListener) {
            mFirebaseAuth.addAuthStateListener(mAuthStateListener);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null != mAuthStateListener) {
            mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
        }
    }
查看更多
▲ chillily
3楼-- · 2020-06-24 06:56

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.

查看更多
登录 后发表回答