I want to retrieve the SMS messages from the device and display them?
Google Play services has two APIs you can use to streamline the SMS-based verification process
SMS Retriever API
Provides a fully automated user experience, without requiring the user to manually type verification codes and without requiring any extra app permissions and should be used when possible. It does, however, require you to place a custom hash code in the message body, so you must have control over server side as well.
Request SMS Verification in an Android App
Perform SMS Verification on a Server
SMS User Consent API
Does not require the custom hash code, however require the user to approve your app's request to access the message containing the verification code. In order to minimize the chances of surfacing the wrong message to the user, SMS User Consent
will filter out messages from senders in the user's Contacts list.
The SMS User Consent API
is part of Google Play Services. To use it you’ll need at least version 17.0.0
of these libraries:
implementation "com.google.android.gms:play-services-auth:17.0.0"
implementation "com.google.android.gms:play-services-auth-api-phone:17.1.0"
Step 1: Start listening for SMS messages
SMS User Consent will listen for incoming SMS messages that contain a one-time-code for up to five minutes. It won’t look at any messages that are sent before it’s started. If you know the phone number that will send the one-time-code, you can specify the senderPhoneNumber
, or if you don’t null
will match any number.
smsRetriever.startSmsUserConsent(senderPhoneNumber /* or null */)
Step 2: Request consent to read a message
Once your app receives a message containing a one-time-code, it’ll be notified by a broadcast. At this point, you don’t have consent to read the message — instead you’re given an Intent
that you can start to prompt the user for consent. Inside your BroadcastReceiver
, you show the prompt using the Intent
in the extras
.
When you start that intent, it will prompt the user for permission to read a single message. They’ll be shown the entire text that they will share with your app.
val consentIntent = extras.getParcelable(SmsRetriever.EXTRA_CONSENT_INTENT)
startActivityForResult(consentIntent, SMS_CONSENT_REQUEST)
Step 3: Parse the one-time-code and complete SMS Verification
When the user clicks “Allow”
— it’s time to actually read the message! Inside of onActivityResult
you can get the full text of the SMS Message from the data:
val message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
You then parse the SMS message and pass the one-time-code to your backend!