Search code examples
androidbroadcastreceiversms

Broadcast Receiver is not receiving SMS from Google SMS retriever API


I am trying to automatically fetch OTP from google sms retriever API but I am not getting any OTP in my broadcast receiver. Here's the details:

build.gradle:

implementation "com.google.android.gms:play-services-auth-api-phone:17.3.0"
     implementation 'com.google.android.gms:play-services-auth:17.0.0'
     implementation 'com.google.android.gms:play-services-gcm:17.0.0'
     implementation 'com.google.android.gms:play-services-base:17.0.0'

Manifest file:

 <receiver android:name=".reciver.MySMSBroadcastReceiver" android:exported="true">
            <intent-filter>
                <action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED"/>
            </intent-filter>
        </receiver>

BroadCast receiver class:

class MySMSBroadcastReceiver : BroadcastReceiver() {
    private val TAG = "MySMSBroadcastReceiver"

//    private var otpReceiver: OTPReceiveListener? = null
//
//    fun initOTPListener(receiver: OTPReceiveListener) {
//        this.otpReceiver = receiver
//    }

    override fun onReceive(context: Context, intent: Intent) {
        if (SmsRetriever.SMS_RETRIEVED_ACTION == intent.action) {
            val extras = intent.extras
            val status = extras?.get(SmsRetriever.EXTRA_STATUS) as Status
            Log.e("OTP_Message","hdhjvcj")

            when (status.statusCode) {
                CommonStatusCodes.SUCCESS -> {
                    // Get SMS message contents
                    var otp: String = extras.get(SmsRetriever.EXTRA_SMS_MESSAGE) as String
                    Log.e("OTP_Message", otp)
                    // Extract one-time code from the message and complete verification
                    // by sending the code back to your server for SMS authenticity.
                    // But here we are just passing it to MainActivity
//                    if (otpReceiver != null) {
//                        otp = otp.replace("<#> Your ExampleApp code is: ", "").split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
//                        otpReceiver!!.onOTPReceived(otp)
//                    }
                }

                CommonStatusCodes.TIMEOUT ->{
                    Log.e(TAG,"TimedOut")
                }
                    // Waiting for SMS timed out (5 minutes)
                    // Handle the error ...
//                    otpReceiver!!.onOTPTimeOut()
            }
        }
    }
}

Activity:

val mSmsBroadcastReceiver = MySMSBroadcastReceiver()
val intentFilter = IntentFilter()
intentFilter.addAction(SmsRetriever.SMS_RETRIEVED_ACTION)
applicationContext.registerReceiver(mSmsBroadcastReceiver, intentFilter)

Below method to initiate:

private fun startSMSRetrievingProcess(){
        val client = SmsRetriever.getClient(this)
        val task = client.startSmsRetriever()
        task.addOnSuccessListener {
            Log.e(TAG,"SMS received")

            // Successfully started retriever, expect broadcast intent
            // ...
        }

    task.addOnFailureListener {
        Log.e(TAG,"SMS received failure")
        // Failed to start retriever, inspect Exception for more details
        // ...
    }
}

OTP format: 123456 is OTP for your application.

I am getting the log inside task.addOnSuccessListener getting printed but not inside the broadcast receiver. Please help me out. I am trying this program on Nougat but want compatibility for all versions.


Solution

  • Per documentation, the SMS must include your app's hash, which is generated from your app's package name and public cert used to sign it. The hash generation is described here, summary from that site:

    The following command computes the hash string from your app's production keystore:

    keytool -exportcert -alias PlayDeploymentCert -keystore MyProductionKeys.keystore | xxd -p | tr -d "[:space:]" | echo -n com.example.myapp cat | sha256sum | tr -d "[:space:]-" | xxd -r -p | base64 | cut -c1-11

    So the SMS message should be like this: 123456 is OTP for your application FA+9qCX9VSu