Вы можете сделать, как показано ниже, в вашем onReceive,
override fun onReceive(context: Context, intent: Intent) {
val data = intent.extras
if (data!!.get("pdus") != null) {
val pdus = data!!.get("pdus") as Array<Any>
for (i in pdus.indices) {
val smsMessage = SmsMessage.createFromPdu(pdus[i] as ByteArray)
val sender = smsMessage.displayOriginatingAddress
val messageBody = smsMessage.messageBody
if (messageBody.toLowerCase().contains("please use the verification code", ignoreCase = true)) {
try {
mListener!!.messageReceived(parseCode(messageBody))
}catch (e:NullPointerException)
{
}
}
}
}
}
======
Parser как ниже
======
private fun parseCode(msg: String): String {
var upToNCharacters: String? = null
try {
var message = msg
var part = arrayOf<String>()
try {
part = message.split("(?<=\\D)(?=\\d)".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
} catch (e: Exception) {
e.printStackTrace()
}
message = message.replace("FLAG", "")
upToNCharacters = part[1].substring(0, Math.min(part[1].length, 6))
Log.i("---->", upToNCharacters)
} catch (e: Exception) {
}
return upToNCharacters!!
}
=====
Ваш интерфейс похож на ниже
interface SmsListener {
fun messageReceived(messageText: String)
}
Напишите ниже в своем файле манифеста
Manifest.xml
<receiver android:name=".common.SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
В вашем классе onResume
val receiver = ComponentName(this, SmsReceiver::class.java!!) //created SMSLog class above!
val pm = this.packageManager
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP)
try {
this.registerReceiver(smsReceiver, android.content.IntentFilter("android.provider.Telephony.SMS_RECEIVED"))
} catch (e: Exception) {
}
и в вашем onStop () отмените регистрацию вещательного приемника
override fun onStop() {//
super.onStop()
try {
unregisterReceiver(smsReceiver)
} catch (e: Exception) {
}
disableBroadcastReceiver()
}