How to Request SMS Verification in an Android App

June 18, 2022

Are you interested in being able to automatically verify phone numbers for both client and server portions? Being a vital part of verification flow, in this article we’ll review what SMS broadcast API is as well as walk you through how to request SMS verification, specifically within an Android App. We’ll also review the benefits of renting a phone number if you’re working through authenticating multiple verifications and how to get a number for Whatsapp verification.

How to Request SMS Verification in an Android App (non-infographic)

What is SMS Broadcast API

SMS API is a well-defined software and its interface enables different variations of code to send messages via a SMS gateway. Although this only works with short messages the infrastructures from text form (SMS) versus internet communications are for the most part, divided, an SMS API or SMS broadcast API works to connect the two so that phone companies and telecommunication carriers can cast a wider net. There are also two key APIs that allow you to send SMS messages.

Telesign SMS API

The telesign SMS API is great for delivery notification reminders, sending one-time verification codes and passwords, private text messages or end-to-end encryption (similar to Whatsapp’s features) and Google’s two-factor authentication.

In short, Telesign SMS is great for:

Delivery Notifications One-Time Verification Purposes End-to-End Encryption Two-Factor Authentication

Due to its one-time verification purposes, we’d recommend renting a U.S. based phone number solely for authentication purposes through a trusted and legitimate source like Tardigrada.io.

Twilio SMS API

Twilio SMS is great for sending shortcodes or intuitive text message delivery. It’s easy to use and works with “smart” content or being able to identify what type of content it’s working with. Twilio also allows you to automatically find information about phone numbers and decreases the likelihood that your SMS text will go undelivered. Although it can recognize several different types of data like:

  • Caller Name
  • Information About Your Carrier
  • Region-Specific Phone Information

You may not want your personal information or personal phone number up for grabs by Twilio’s API. If this is the case we recommend renting a phone number within the United States. We’d also recommend this if you’re trying to verify multiple accounts or just if you want to keep your personal information more private.

How to Request SMS Verification (for Android)

Before starting the process, make sure your app’s build file has the following values, as outlined by Google Identity:

  • A minSdkVersion of 19 or higher
  • A compileSdkVersion of 28 or higher

Configure your application by bringing up your project-level build.gradle file allowing for Google’s Maven central and main repository in your buildscript and allproject categories:

buildscript {
    repositories {
        google()
        mavenCentral()
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

You’ll also want to add some dependencies as listed here:

dependencies {
  implementation 'com.google.android.gms:play-services-auth:20.2.0'
  implementation 'com.google.android.gms:play-services-auth-api-phone:18.0.1'
}

1. Get Your User’s Phone Number

If you’re still gearing up for your applications launch or are still looking for viable users a great way to fully test your application is by renting a phone number through Tardigrada.io. This allows you to test features within the application without the hassle of creating a new phone number or going through an alternative cell phone carrier.

Here’s how to use hint picker after you’ve rented a phone number to test your application:

// Construct a request for phone numbers and show the picker
private void requestHint() {
    HintRequest hintRequest = new HintRequest.Builder()
           .setPhoneNumberIdentifierSupported(true)
           .build();

    PendingIntent intent = Auth.CredentialsApi.getHintPickerIntent(
            apiClient, hintRequest);
    startIntentSenderForResult(intent.getIntentSender(),
            RESOLVE_HINT, null, 0, 0, 0);
}

// Obtain the phone number from the result
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if (requestCode == RESOLVE_HINT) {
      if (resultCode == RESULT_OK) {
          Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
          // credential.getId();  <-- will need to process phone number string
      }
  }
}

2. Start Your SMS Retriever

After you’ve completed step one, you’ll need to verify your user’s phone number to be able to gain access to the SmsRetrieverClient. Like we stated above, this can be especially cumbersome if you’re still gaining users. Consider an alternative and rent a phone number for 30 minutes or more, solely for authentication purposes. Afterwards, call startSmsRetriever, attach failure and attach success listeners to the retrieval task like so:

// Get an instance of SmsRetrieverClient, used to start listening for a matching
// SMS message.
SmsRetrieverClient client = SmsRetriever.getClient(this /* context */);

// Starts SmsRetriever, which waits for ONE matching SMS message until timeout
// (5 minutes). The matching SMS message will be sent via a Broadcast Intent with
// action SmsRetriever#SMS_RETRIEVED_ACTION.
Task<Void> task = client.startSmsRetriever();

// Listen for success/failure of the start Task. If in a background thread, this
// can be made blocking using Tasks.await(task, [timeout]);
task.addOnSuccessListener(new OnSuccessListener<Void>() {
  @Override
  public void onSuccess(Void aVoid) {
    // Successfully started retriever, expect broadcast intent
    // ...
  }
});

task.addOnFailureListener(new OnFailureListener() {
  @Override
  public void onFailure(@NonNull Exception e) {
    // Failed to start retriever, inspect Exception for more details
    // ...
  }
});

This portion may take up to 5 minutes for the SMS message to gain a unique string that ID’s your application.

3. Send the Number to Your Server and Receive Verification Messages

This step is fairly easy as long as you have a phone number to work off of and you can start verifying your user’s phone number using the HTTP POST request. This will allow the verification message to be generated and send it to the number you’ve rented above.

Afterwards you can go ahead and receive verification text messages. If you don’t want to use a real user to test your app a rented phone number can be the perfect solution, especially if you’re still troubleshooting and don’t want to use a real consumer or your real phone number.

After you get the sms broadcast API and the note that SmsRetriever.SMS_Retrieved_Action intent within the text message you can go ahead and Perform SMS Verification on the Server.

Within the BroadcastReciever and onReceive handler you can get these Intent’s extras:

/**
 * BroadcastReceiver to wait for SMS messages. This can be registered either
 * in the AndroidManifest or at runtime.  Should filter Intents on
 * SmsRetriever.SMS_RETRIEVED_ACTION.
 */
public class MySMSBroadcastReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
    if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
      Bundle extras = intent.getExtras();
      Status status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);

      switch(status.getStatusCode()) {
        case CommonStatusCodes.SUCCESS:
          // Get SMS message contents
          String message = (String) extras.get(SmsRetriever.EXTRA_SMS_MESSAGE);
          // Extract one-time code from the message and complete verification
          // by sending the code back to your server.
          break;
        case CommonStatusCodes.TIMEOUT:
          // Waiting for SMS timed out (5 minutes)
          // Handle the error ...
          break;
      }
    }
  }
}

4. Get Your One-Time Verification Code from Your Server

After you get your text verification simply use a type of logic or regular expression to get your verification code from your server. The format will differ from application to application but done correctly it will be sent to your server in a secure fashion. Afterwards your server should show that the phone number was verified. It’s important to note that this one-time code is within your server and not the client’s application.

We hope this guide on how to request sms code and verify phone sms specifically for Android applications was helpful. If you’re thinking of doing a run through of your Android-specific app before your product or application launch, consider renting a phone number for authentication purposes instead of doing a costly alternative. Join the thousands using Tardigrada.io, today.