Authenticate with Firebase anonymously on Android
You have the beautiful application/game that you developed with love. You thought about every detail. Usually, those details require you to save your users’ data on the cloud. The problem is that you do not want to annoy your new users by forcing them to sign up for the system that they just saw. What do you do? What can you do?
Manual approach
You can keep your users’ data locally and you can upload their data to their account whenever they decide to sign up. What do you have to implement to do this?
- Local db/file etc
- Synchronization code on sign up operation
It does not look so bad. But still, firebase has a better, easier solution.
Firebase approach
Firebase already thought about this requirement and developed a solution for it. We cannot see the actual code since it is obfuscated but it shouldn’t be so different than the ‘manual solution’ that you are going to implement.
Ok! What do you have to implement for the Firebase solution?
- One method call to get the anonymous user
- One method call to link the actual user
Show me the code!
Get anonymous user:
private lateinit var mAuth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mAuth = FirebaseAuth.getInstance()
//...
}override fun onStart() {
super.onStart()
val currentUser = mAuth.currentUser
if (currentUser != null) {
updateUi(currentUser)
} else {
mAuth.signInAnonymously()
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val user = mAuth.currentUser
user?.let { updateUi(it) }
} else {
Toast.makeText(
this@MainActivity,
"Authentication failed.",
Toast.LENGTH_SHORT)
.show()
}
}
}
}
Link the actual user:
After getting the user credential from Google, Facebook, or any other provider; all you have to do is calling a single method.
mAuth.getCurrentUser().linkWithCredential(credential)
Have fun with the free implementation of the anonymous authentication. Do not forget to follow and clap 👏
Here is the official firebase documentation link.