In this article, you will learn how to read sms and verify otp automatically in android. We are using SMS user consent api for reading sms to verify otp automatically in android.
SMS verification is mandatory nowadays if we use mobile number of user for identification in our apps. For otp verification, User need to read sms from messages app and submit otp in our android apps. To prevent this issue, android provides sms user consent api to read sms and verify otp automatically.
SMS user consent api first displays prompt to user to request read incoming message. So our android apps can read sms and verify otp automatically. If user grants this permission through allow button then we are reading sms to verify otp using sms user consent api.
There are some rules for incoming message. Incoming message must contain one time code. Code should be 4–10 digit alphanumeric and 1 digit must be a number. This message should not be received from any of our contacts. SMS user consent api wait for reading sms for five minutes. If message is not received within five minutes then api throws timeout error.
Add following dependencies in your app level build.gradle file
Retrieve phone number of user
First we need to get phone number of user to read incoming message using sms user consent api. Now we display picker to select phone number in our apps. So we can obtain user’s phone number.
Start Reading SMS To Verify OTP Listener
Now we need to detect incoming sms messages to verify otp. So we start this listener after getting user phone number. If you are knowing sender’s phone number then you can pass it in this listener otherwise you can pass null.
Handle Reading SMS To Verify OTP
After detecting incoming message, we need to handle this message using broadcast receiver to verify otp automatically. Our incoming message should follow all rules as I mentioned earlier otherwise prompt will not be displayed to user.
Now we need to extract verification code after getting from incoming message. So we can display verification code in our UI.