Kotlin-API 27及更高版本-SMS广播接收器

时间:2019-01-07 08:06:28

标签: kotlin sms broadcast receiver

我正在开发一个应用程序,该应用程序将接收到的SMS内容转换为几个字符串,并将其发送到服务器上的数据库中。我已经设置了广播接收器,并且在所有运行API26及更低版本的设备上都可以正常工作。对于更高版本,我需要手动禁用和启用应用程序设置中的权限才能运行几分钟,然后它不再对新SMS做出反应。

我不想在活动中注册我的接收器,因为即使应用未运行,它也必须对所有收到的SMS做出反应...而且这与隐式接收器完美配合...

有人知道我在做什么错,或者什么是适当的解决方法?

谢谢!

清单声明

<receiver
        android:name=".WakeupReceiver"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.BROADCAST_SMS"

        android:stopWithTask="false">
        <intent-filter android:priority="2147483643">
            <category android:name="android.intent.category.DEFAULT" />

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

类声明:

class WakeupReceiver : BroadcastReceiver() {


override fun onReceive(context: Context, intent: Intent) {

        val (smsContact, smsBody) = getSMSContent(intent)
        if (smsContact=="Utils.myNumber") {
           Log.d("Log","SMS received!")
        }

    }



private fun getSMSContent(intent: Intent): Pair<String, String> {
    val data = intent.extras
    val pdusObj = data!!.get("pdus") as Array<*>
    for (i in pdusObj.indices) {
        val currentMessage = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
            Telephony.Sms.Intents.getMessagesFromIntent(intent)[0]
        else SmsMessage.createFromPdu(pdusObj[0] as ByteArray)

        // TODO: Here we get the all information about SMS.
        //Apply your conditions and logic here to filter your SMS from various SMS
        // and extract your content from message body

        val phoneNumber = currentMessage.displayOriginatingAddress
        Log.e("phoneNumber", phoneNumber)

        val senderNum = phoneNumber
        Log.e("senderNum", senderNum)

        val smsContent = currentMessage.displayMessageBody

        return Pair(senderNum, smsContent)
    }
    return Pair("","")
}

}

0 个答案:

没有答案