简体   繁体   中英

Parse incoming SMS Android (API 26)

I need to parse incoming message to the app, but I don't understand how to do it. This my receiver:

class SmsReceiver: BroadcastReceiver() {
companion object {
    val ACTION = "android.provider.Telephony.SMS_RECEIVED"
    val BANKMANE = ""
    val SMS_BODY = "sms_body"
    val PDUS = "pdus"
}

override fun onReceive(context: Context, intent: Intent) {
    if (intent.action != null &&
            ACTION.compareTo(intent.action, false) === 0) {
        val pduArray = intent.extras.get(PDUS) as Array<Any>
        val messages = arrayOfNulls<SmsMessage>(pduArray.size)
        for (i in pduArray.indices) {
            messages[i] = SmsMessage.createFromPdu(pduArray[i] as ByteArray)
        }
        val sms_from = messages[0]!!.getDisplayOriginatingAddress()
        if (sms_from.equals(BANKMANE, ignoreCase = true)) {
            val bodyText = StringBuilder()
            for (i in 0 until messages.size) {
                bodyText.append(messages[i]!!.getMessageBody())
            }
            val body = bodyText.toString()
            val mIntent = Intent(context, SmsService::class.java)
            mIntent.putExtra(SMS_BODY, body)
            context.startService(mIntent)

            abortBroadcast()
        }

    }
}}

This my Manifest.xml :

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.RECEIVE_SMS"/>

<application
   ...........
    <receiver android:name=".smsParcer.SmsReceiver">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
        </intent-filter>
    </receiver>
</application>

I really don't understand how to use this receiver, and how to correctly make the Mainfest.xml . I can't find some examples on how to use the receiver. I need to understand how to tie the receiver to some activity. I would be grateful for any help.

You can do like below, In your 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 is like below

======

    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!!
}

=====

Your interface is like below

interface SmsListener {
   fun messageReceived(messageText: String)

}

Write below in your manifest file

Manifest.xml

        <receiver android:name=".common.SmsReceiver">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

In your class 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) {
    }

and in your onStop() unregister your broadcastReceiver

    override fun onStop() {//
    super.onStop()
    try {
        unregisterReceiver(smsReceiver)
    } catch (e: Exception) {

    }
    disableBroadcastReceiver()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM