23

我已经使用此处的指南在我的应用程序中成功实现了 SMS 检索器。我的代码工作正常,并且在许多设备中自动填充了 otp,但有些设备(如 vivo v15 pro、redmi note 4)无法正常工作(BroadcastReceiver 的 onReceive() 未触发)。我在这里附上了我的代码。检查并让我知道您是否对此有任何解决方案。谢谢

清单.xml

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

SMSRetrieverBroadcastReceiver.kt

   class SMSRetrieverBroadcastReceiver : BroadcastReceiver() {



companion object{
    private var otpReceiver: OtpReceiver? = null
    fun initOTPListener(receiver: OtpReceiver) {
        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

        when (status.statusCode) {
            CommonStatusCodes.SUCCESS -> {
                // Get SMS message contents
                var otp: String = extras.get(SmsRetriever.EXTRA_SMS_MESSAGE) as String
                Timber.d("OTP_Message "+otp)
              if(otpReceiver != null) {
                    otpReceiver!!.onOTPReceived(otp)
                }
            }

            CommonStatusCodes.TIMEOUT -> {
                // Waiting for SMS timed out (5 minutes)
                // Handle the error ...
                if(otpReceiver != null) {
                    otpReceiver!!.onOTPTimeOut()
                }
        }
    }
}}

MainActivity.kt

fun startListeningForSMS() {
    SMSRetrieverBroadcastReceiver.initOTPListener(this)
    startSmsListener()
}


private fun startSmsListener() {
    val client = SmsRetriever.getClient(mContext)
    val task = client.startSmsRetriever()
    task.addOnSuccessListener {
        Timber.d("Success")
    }

    task.addOnFailureListener {
        Timber.d("Failed")
    }
}

override fun onOTPReceived(otp: String) {
    setReceivedOtp(otp)
}

override fun onOTPTimeOut() {
    setReceivedOtp(null)
}
4

2 回答 2

2

转到 Messeges-单击左上角的 (:) -> 转到设置-> 禁用 Otp 验证预防。在我的情况下它工作得很好。

于 2021-03-04T06:00:30.107 回答
0

你能检查一下这个意图过滤器操作吗:

 <action android:name="android.provider.Telephony.SMS_RECEIVED" /> 
于 2021-01-04T06:50:42.353 回答