Android auto-populate OTP in Kotlin

Google prohibits the SMS/CALL_LOG related permission if your app is not mainly for the phone call, text purpose. Or you cannot send the updated app via Google Play anymore. But for some app, we need to verify the user’s account via their phone. And in the user’s perspective, we should make it as much as easier to do.

There is an alternative way— SMS Retrieve API

1. You need to add one auth dependency.

2. Add request hint to your Activity or Fragment. The best way is to use the hint picker pop up. The user can choose the phone numbers stored on the device. Then the user doesn’t need to input the phone manually. Like the below RequestHintActivity sample:

3. Backend side will implement the SMS message like this. The last line shows the hash string encrypts by your App key store. This is for android system know which app needs to receive the SMS message. How to generate the hash string can see here. (Be aware of that maybe you have staging and production. The key might be different.)

4. Add one SMSBroadcastReceiver to receive the SMS message. Then we can register the SMS receiver dynamically.

For parseSMSCode , I will suggest you write some test to make sure the parse method is working properly.

5. Add startSMSRetrieve method in your Activity/Fragment to start SMS retriever.

That’s it. We don’t need any SMS or CALL_LOG related permission then we can have an auto-populate OTP feature. Enjoy it :)

An Android developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store