2

I implemented the Android SMS Verification API on activities and fragments on the same project and it went well. My problem is with fragments in tabs. No matter what I do, onActivityResult always returns result code 0 when "Allow" is pressed. Here's my lot of code which was also implemented and tested to be working on the activities and fragments.

override fun onStart() {
    super.onStart()
    registerToSmsBroadcastReceiver()
}

override fun onStop() {
    myActivity.unregisterReceiver(smsBroadcastReceiver)
    super.onStop()
}

private fun startSmsUserConsent() {
    SmsRetriever.getClient(myActivity).also {
        it.startSmsUserConsent(null)
                .addOnSuccessListener {
                    Log.d("LISTENING", "SUCCESS")
                }
                .addOnFailureListener {
                    Log.d("LISTENING", "FAIL")
                }
    }
}

private fun registerToSmsBroadcastReceiver() {
    smsBroadcastReceiver = SmsBroadcastReceiver().also {
        it.smsBroadcastReceiverListener =
                object : SmsBroadcastReceiver.SmsBroadcastReceiverListener {
                    override fun onSuccess(intent: Intent?) {
                        intent?.let { context -> startActivityForResult(context, REQ_USER_CONSENT) }
                    }

                    override fun onFailure() {
                    }
                }
    }

    val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION)
    myActivity.registerReceiver(smsBroadcastReceiver, intentFilter)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
        REQ_USER_CONSENT -> {
            if ((resultCode == Activity.RESULT_OK) && (data != null)) {
                val message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
                val code = message?.let { fetchVerificationCode(it) }
                otpField.setText(code)
            }
        }
    }
}

private fun fetchVerificationCode(message: String): String {
    return Regex("(\\d{6})").find(message)?.value ?: ""
}

Oh, and startSmsUserConsent() is called whenever I call for the API to send an OTP. Anything I missed?

Thank you.

Lendl Leyba
  • 2,287
  • 3
  • 34
  • 49

1 Answers1

0

I solved the issue by handling the OTP SMS Retrieval on the activity instead of on the fragment, then passed on the fragment if need be.

Lendl Leyba
  • 2,287
  • 3
  • 34
  • 49