vendredi 20 décembre 2019

Allow authenticated users only to access any activity using Firebase Authentication in Android

I am developing an app by using Firebase Authentication. In my app all activities should be accessed by an authenticated user only. To do this I have this portion of code in all my activities:

firebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                // If user is logged out, bring him to LoginActivity
                final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                if(user == null){
                    Intent intent = new Intent(ConnectionsActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        };

I realize that this is not a good way to do it since my code is not DRY anymore and I'm having to copy paste this portion to all my activities. I am thinking of implementing a singleton class, but I'm not sure how it will work in Android framework. Is there a better way to make the user to be authenticated without repeating this code?

Aucun commentaire:

Enregistrer un commentaire