Skip to content

Instantly share code, notes, and snippets.

@puf
Created January 5, 2021 23:35
Show Gist options
  • Save puf/9818068b3be173c40cdcf56d2cc59029 to your computer and use it in GitHub Desktop.
Save puf/9818068b3be173c40cdcf56d2cc59029 to your computer and use it in GitHub Desktop.
Listen for authentication state in Android
// In Firebase it is often better to *react* to authentication state
// changes, instead getting the current authentication state everywhere.
// To respond to auth state changes, use an auth state change listener
// like this:
FirebaseAuth auth = FirebaseAuth.getInstance();
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());
}
}
});
// In Firebase it is often better to *react* to authentication state
// changes, instead getting the current authentication state everywhere.
// To respond to auth state changes, use an auth state change listener
// like this:
val auth = FirebaseAuth.getInstance();
auth.addAuthStateListener {
Log.i("firebase", "AuthState changed to ${it.currentUser?.uid}")
if (it.currentUser != null) {
... do something with the signed in user
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment