You can use Firebase Authentication to sign in a user by sending an SMS message to the user’s phone. The user signs in using a one-time code contained in the SMS message.
- Add Firebase to your Android project.
- Add the dependency for Firebase Authentication to your app-level
build.gradle
file:1compile 'com.google.firebase:firebase-auth:11.0.1' - If you haven’t yet connected your app to your Firebase project, do so from the Firebase console.
- If you haven’t already set your app’s SHA-1 hash in the Firebase console, do so. See Authenticating Your Client for information about finding your app’s SHA-1 hash.
Create a custom layout for register user contact number, user can verify the authentication code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="webkul.opencart.mobikul.PhoneNumberVerifier"> <LinearLayout android:layout_width="match_parent" android:padding="20dp" android:layout_height="wrap_content" android:orientation="vertical"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:textAlignment="center" android:id="@+id/contact" android:hint="@string/number"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAlignment="center" android:id="@+id/contact_btn" android:padding="@dimen/button_padding" android:layout_gravity="center" android:text="@string/continue1"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:textAlignment="center" android:id="@+id/verify_edt" android:hint="@string/verify"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAlignment="center" android:id="@+id/verify_btn" android:padding="@dimen/button_padding" android:layout_gravity="center" android:text="@string/continue1"/> </LinearLayout> </RelativeLayout> |
Then pass the phone number to PhoneAuthProvider.verifyPhoneNumber method to request the Firebase to verify the contact number. For example:
1 2 3 4 5 6 |
PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, // Phone number to verify 60, // Timeout duration TimeUnit.SECONDS, // Unit of timeout this, // Activity (for callback binding) mCallbacks); // OnVerificationStateChangedCallbacks |
When you call PhoneAuthProvider.verifyPhoneNumber
, you must also provide an instance of OnVerificationStateChangedCallbacks
, which contains implementations of the callback functions that handle the results of the request. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential credential) { // This callback will be invoked in two situations: // 1 - Instant verification. In some cases the phone number can be instantly // verified without needing to send or enter a verification code. // 2 - Auto-retrieval. On some devices Google Play services can automatically // detect the incoming verification SMS and perform verificaiton without // user action. Log.d(TAG, "onVerificationCompleted:" + credential); signInWithPhoneAuthCredential(credential); } @Override public void onVerificationFailed(FirebaseException e) { // This callback is invoked in an invalid request for verification is made, // for instance if the the phone number format is not valid. Log.w(TAG, "onVerificationFailed", e); if (e instanceof FirebaseAuthInvalidCredentialsException) { // Invalid request // ... } else if (e instanceof FirebaseTooManyRequestsException) { // The SMS quota for the project has been exceeded // ... } // Show a message and update the UI // ... } @Override public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) { Log.d(TAG, "onCodeSent:" + verificationId); // Save verification ID and resending token so we can use them later mVerificationId = verificationId; mResendToken = token; // ... } }; |
After the user enters the verification code that Firebase sent to the user’s phone, create a PhoneAuthCredential
object, using the verification code to onCodeSent
or onCodeAutoRetrievalTimeOut
callback.
1 |
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code); |
After user verify it’s authentication code pass the credential instanace of PhoneAuthProvider to signInWithPhoneAuthCredential(credential) method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) { FirebaseAuth.getInstance().signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d("PhoneVERifier", "signInWithCredential:success"); startActivity(new Intent(PhoneNumberVerifier.this,MainActivity.class)); finish(); FirebaseUser user = task.getResult().getUser(); FirebaseAuth.getInstance().signOut(); // ... } else { // Sign in failed, display a message and update the UI Log.w("PhoneVERifier", "signInWithCredential:failure", task.getException()); if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { // The verification code entered was invalid } } } }); } |
Keep Coding and Keep Sharing 🙂