Thank to @Vineet Shukla (the accepted answer) and @Ruchir Baronia (found the issue in the accepted answer), below is the Kotlin
version:
Add permission:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
Register BroadcastReceiver in AndroidManifest:
<receiver
android:name=".receiver.SmsReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="2332412">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
Add implementation for BroadcastReceiver:
class SmsReceiver : BroadcastReceiver() {
private var mLastTimeReceived = System.currentTimeMillis()
override fun onReceive(p0: Context?, intent: Intent?) {
val currentTimeMillis = System.currentTimeMillis()
if (currentTimeMillis - mLastTimeReceived > 200) {
mLastTimeReceived = currentTimeMillis
val pdus: Array<*>
val msgs: Array<SmsMessage?>
var msgFrom: String?
var msgText: String?
val strBuilder = StringBuilder()
intent?.extras?.let {
try {
pdus = it.get("pdus") as Array<*>
msgs = arrayOfNulls(pdus.size)
for (i in msgs.indices) {
msgs[i] = SmsMessage.createFromPdu(pdus[i] as ByteArray)
strBuilder.append(msgs[i]?.messageBody)
}
msgText = strBuilder.toString()
msgFrom = msgs[0]?.originatingAddress
if (!msgFrom.isNullOrBlank() && !msgText.isNullOrBlank()) {
//
// Do some thing here
//
}
} catch (e: Exception) {
}
}
}
}
}
Sometime event fires twice so I add mLastTimeReceived = System.currentTimeMillis()