问题描述
我在我的应用中实现 SMS 检索器同意 API 时收到此“接收广播意图时出错”。 这是我的片段中的广播接收器代码:
private val smsverificationReceiver = object : broadcastReceiver() {
override fun onReceive(context: Context,intent: Intent) {
if (SmsRetriever.SMS_RETRIEVED_ACTION == intent.action) {
val extras = intent.extras
val smsRetrieverStatus = extras?.get(SmsRetriever.EXTRA_STATUS) as Status
when (smsRetrieverStatus.statusCode) {
CommonStatusCodes.SUCCESS -> {
// Get consent intent
Log.d("sms","in success")
val consentIntent = extras?.getParcelable<Intent>(SmsRetriever.EXTRA_CONSENT_INTENT)
try {
Log.d("sms","in success try")
// Start activity to show consent dialog to user,activity must be started in
// 5 minutes,otherwise you'll receive another TIMEOUT intent
startActivityForResult(consentIntent,SMS_CONSENT_REQUEST)
} catch (e: ActivityNotFoundException) {
// Handle the exception ...
Log.d("sms","Exception")
}
}
CommonStatusCodes.TIMEOUT -> {
// Time out occurred,handle the error.
Log.d("sms","Timeout")
}
}
}
}
}
首先我启动监听器,在监听器成功后我注册了广播接收器
这是我的听众
private fun startSmsListener(){
val task = context?.let { SmsRetriever.getClient(it).startSmsUserConsent(null /* or null */) }
task?.addOnSuccessListener {
showToast("Sms auto detection started")
Log.d("sms","Sms auto detection started")
val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION)
context?.registerReceiver(smsverificationReceiver,intentFilter)
}
task?.addOnFailureListener {
showToast("Sms auto detection Failed")
Log.d("sms","Sms auto detection Failed")
}
}
最后我在 onActivityResult 中得到结果
override fun onActivityResult(requestCode: Int,resultCode: Int,data: Intent?) {
super.onActivityResult(requestCode,resultCode,data)
when (requestCode) {
// ...
SMS_CONSENT_REQUEST ->
// Obtain the phone number from the result
if (resultCode == Activity.RESULT_OK && data != null) {
// Get SMS message content
val message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
// Extract one-time code from the message and complete verification
// `message` contains the entire text of the SMS message,so you will need
// to parse the string.
//val oneTimeCode = parSEOneTimeCode(message) // define this function
Log.d("OTP detected",message)
//txt_otp.setText(oneTimeCode)
// send one time code to the server
} else {
// Consent denied. User can type OTC manually.
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)