How to implement Anonymous authentication in android using Firebase
Firebase provides many ways to authenticate users into your app, One of them is Anonymous login. If the user wants to use your app without providing any info, in that case, Anonymous login comes handy.
Firebase has well-documented documentation, if you want more information on Firebase authentication you can take a look in the documentation
Let’s start our tutorial:
Step 1) First of all we have to initialize Firebase Auth instance in your activity’s onCreate method
private FirebaseAuth mAuth;
// Put below line in onCreate method
mAuth = FirebaseAuth.getInstance();
Step 2) Set up an AuthStateListener
that responds to changes in the user's sign-in state at runtime ( Here you will get a callback from firebase when the user registered as anonymously.)
private FirebaseAuth.AuthStateListener mAuthListener;@Override
protected void onCreate(Bundle savedInstanceState) {// active listen to user logged in or not.
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
} }
};
}// Add Auth state listener in onStart method.
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}// stop listener in onStop
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
Step 3) Finally, call signInAnonymously
to sign in as an anonymous user
mAuth.signInAnonymously()
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "Auth : " +task.isSuccessful()); if (!task.isSuccessful()) {
Log.w(TAG, "Failed : ", task.getException());
Toast.makeText(MainActivity.this, "Login failed.", Toast.LENGTH_SHORT).show();
} else {
// start an acitivty here}
}
});
Make sure you start an activity or give feedback to the user when the user is signed in :)
The above code will work perfectly and you’ll get your user signed in using anonymous auth.
Follow for more tutorials, and also follow me on Instagram @ankitsuda :)