我已使用here准则在我的应用程序中成功实现了SMS检索器。我的代码运行正常,并且在许多设备上自动填充了otp,但是某些设备(例如vivo v15 pro,redmi注意4)不起作用(无法触发BroadcastReceiver的onReceive())。我在这里附上了我的代码。检查,让我知道您是否对此有任何解决方案。谢谢
Manifest.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)
}
最佳答案
您可以通过以下意图过滤器操作来检查:
<action android:name="android.provider.Telephony.SMS_RECEIVED" />