1

我在同一个项目的活动和片段上实现了 Android SMS 验证 API,并且进展顺利。我的问题是标签中的片段。无论我做什么,当按下“允许”时,onActivityResult 总是返回结果代码 0。这是我的大量代码,它们也被实现和测试以处理活动和片段。

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 ?: ""
}

哦,startSmsUserConsent()每当我调用 API 发送 OTP 时都会调用它。我错过了什么?

谢谢你。

4

1 回答 1

0

我通过在活动而不是片段上处理 OTP SMS 检索解决了这个问题,然后在需要时传递片段。

于 2020-09-25T06:04:52.977 回答