Android Tutorial
Software Setup and Configuration
Android Studio
File Structure
Components
Core Topics
Layout
View
Button
Intent and Intent Filters
Toast
RecyclerView
Fragments
Adapters
Other UI Component
Image Loading Libraries
Date and Time
Material Design
Bars
Working with Google Maps
Chart
Animation
Database
Advance Android
Jetpack
Architecture
App Publish
App Monetization
Firebase Authentication provides a seamless user authentication experience without the need to manage server-side infrastructure. Phone authentication via OTP (One-Time Password) is one of the methods supported by Firebase.
Here's a step-by-step guide to implement Firebase Phone Authentication with OTP:
google-services.json
file.app
directory in Android Studio.Add the Firebase Authentication SDK to your build.gradle
(Module: app):
implementation 'com.google.firebase:firebase-auth:19.2.0'
Ensure you also have the Google services plugin applied at the bottom of your build.gradle
:
apply plugin: 'com.google.gms.google-services'
In your main activity or application class, initialize Firebase:
FirebaseApp.initializeApp(this);
FirebaseAuth auth = FirebaseAuth.getInstance(); PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(@NonNull PhoneAuthCredential credential) { signInWithPhoneAuthCredential(credential); } @Override public void onVerificationFailed(@NonNull FirebaseException e) { // Handle the error, for instance, display a message to the user } @Override public void onCodeSent(@NonNull String verificationId, @NonNull PhoneAuthProvider.ForceResendingToken token) { // Save the verificationId and resending token to use later // Prompt the user to enter the code } }; PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, // Phone number to verify 60, // Timeout duration TimeUnit.SECONDS, // Unit of the timeout this, // Activity (for callback binding) mCallbacks); // OnVerificationStateChangedCallbacks
Once the user has received the OTP and entered it in your app, you can validate it:
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code); signInWithPhoneAuthCredential(credential);
Use the following method to authenticate the user:
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) { auth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success FirebaseUser user = task.getResult().getUser(); // Update UI or navigate to the main activity } else { // Sign in failed, display a message and update the UI } } }); }
Handle any errors during the process, such as invalid codes or expired OTPs, by checking the task.getException()
method in the onComplete
callback.
Remember to also consider edge cases, such as when the user doesn't receive an OTP, allowing them to request another OTP after a reasonable duration.
This is a basic guide. For a production application, you'd also want to handle edge cases, offer more feedback to the user, and ensure a seamless experience across the authentication process.
Implementing OTP verification with Firebase in Android:
PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, // Phone number to verify 60, // Timeout duration TimeUnit.SECONDS, // Unit of timeout this, // Activity (context) callbacks); // Callbacks for verification
Phone Number Authentication with Firebase example code:
FirebaseAuth auth = FirebaseAuth.getInstance(); auth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // User is signed in } else { // Authentication failed } } });
Handling Firebase Phone Authentication callbacks in Android:
PhoneAuthProvider.OnVerificationStateChangedCallbacks callbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential credential) { // Auto-retrieval or instant verification } @Override public void onVerificationFailed(FirebaseException e) { // Verification failed } // Other callback methods };
Handling errors and edge cases in Firebase Phone Authentication:
task.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Handle failure } });