Android Kotlin:当设备收到新短信时监听事件不起作用

Android Kotlin: listening to the event when the device receives a new text message is not working

我正在使用 Android 构建一个 Android 应用程序。在我的应用程序中,即使应用程序已关闭,我也会尝试在设备收到新短信时执行某些操作。基本上,我试图在收到新短信时显示通知。我正在为此使用广播公司。但它没有按预期工作。

这是我的接收器。

class SmsListener:  BroadcastReceiver() {
    private lateinit var notificationManager: NotificationManager
    private lateinit var notificationChannel: NotificationChannel
    lateinit var builder: Notification.Builder
    private val channelId = "i.apps.notifications"
    private val description = "Test notification"
    private lateinit var context: Context

    override fun onReceive(context: Context?, intent: Intent?) {
        this.context = context as Context
        if(intent?.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
            val bundle = intent!!.extras //---get the SMS message passed in---

            var msgs: Array<SmsMessage?>? = null
            var msg_from: String
            if (bundle != null) {
                //---retrieve the SMS message received---
                try {
                    val pdus =
                        bundle["pdus"] as Array<Any>?
                    msgs = arrayOfNulls<SmsMessage>(pdus!!.size)
                    for (i in msgs.indices) {
                        msgs[i] = SmsMessage.createFromPdu(pdus!![i] as ByteArray)
                        msg_from = msgs[i]!!.getOriginatingAddress() as String
                        val msgBody: String = msgs[i]!!.getMessageBody()
                        //@TODO: display the notification. When clicked, redirect the user to the message details activity with a share button

                        if (! msgBody.isNullOrEmpty()) {
                            showNotification(msgBody)
                        }
                    }
                } catch (e: Exception) {

                }
            }
        }
    }

    private fun showNotification(message: String) {
        //@TODO: remove the identifier from the message
        //@TODO: confirm number of characters for message description
        initialiseNotificationManager()
        val intent = Intent(this.context, MessageDetailsActivity::class.java)
        intent.putExtra(MessageDetailsActivity.KEY_MESSAGE, message)
        val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            initialiseNotificationChannel()
            builder = Notification.Builder(this.context, channelId).setContentTitle("22222: New message received.").setContentText(message.take(50)).setSmallIcon(R.drawable.common_google_signin_btn_icon_dark).setLargeIcon(BitmapFactory.decodeResource(this.context.resources, R.drawable
                    .ic_launcher_background)).setContentIntent(pendingIntent)
        }
        notificationManager.notify(12345, builder.build())
    }

    private fun initialiseNotificationChannel(){
        if (! this::notificationChannel.isInitialized) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                notificationChannel = NotificationChannel(channelId, description, NotificationManager .IMPORTANCE_HIGH)
                notificationChannel.lightColor = Color.BLUE
                notificationChannel.enableVibration(true)
                notificationManager.createNotificationChannel(notificationChannel)
            }
        }
    }

    private fun initialiseNotificationManager() {
        if (! this::notificationManager.isInitialized) {
            notificationManager = this.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        }
    }
}

这就是我在 AndroidManifest.xml 文件中注册接收器的方式。

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

这就是我在主程序中注册接收器的方式activity

try {
            // register the broadcast receiver to catch the incoming messages
            var filter = IntentFilter()
            filter.addAction("com.forkthecoup.com22222.SmsListener")
            val receiver: SmsListener = SmsListener()
            registerReceiver(receiver, filter)
            sendBroadcast(Intent("com.forkthecoup.com22222.SmsListener"))
        } catch (e: Exception) {

        }

是的,我已授予该应用接收和发送消息的正确权限。但是当应用程序收到一条新消息时,它不会显示通知。我的代码有什么问题,我该如何解决?

您还没有为 Api 24 添加通知,下面是代码

   private fun showNotification(message: String) {
        //@TODO: remove the identifier from the message
        //@TODO: confirm number of characters for message description
        initialiseNotificationManager()
        val intent = Intent(this.context, MainActivity::class.java)
        intent.putExtra("MainActivity.KEY_MESSAGE", message)
        val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            initialiseNotificationChannel()
            Notification.Builder(this.context, channelId).setContentTitle("22222: New message received.").setContentText(message.take(50)).setSmallIcon(R.drawable.common_google_signin_btn_icon_dark).setLargeIcon(BitmapFactory.decodeResource(this.context.resources, R.drawable
                    .ic_launcher_background)).setContentIntent(pendingIntent)
        } else {
            Notification.Builder(this.context).setContentTitle("22222: New message received.").setContentText(message.take(50)).setSmallIcon(R.drawable.common_google_signin_btn_icon_dark).setLargeIcon(BitmapFactory.decodeResource(this.context.resources, R.drawable
                    .ic_launcher_background)).setContentIntent(pendingIntent)
        }
        notificationManager.notify(12345, builder.build())
    }