【问题标题】:Android Kotlin: listening to the event when the device receives a new text message is not workingAndroid Kotlin:设备收到新短信时监听事件不起作用
【发布时间】:2021-02-27 15:49:46
【问题描述】:

我正在使用 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>

这就是我在主活动中注册接收器的方式

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) {

        }

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

【问题讨论】:

  • 还是同样的通知问题还是你的应用没有通过 BroadCastReceiver 接收到消息?
  • 是应用程序没有在广播接收器中接收到消息。
  • 我在 Api 级别 29 和 30 中测试了您的代码,它运行良好,但我没有实现我手动激活它的权限代码
  • 谢谢。在 API 版本较低的设备上一定是一些通知问题。
  • 现在我已经在 api 21 上测试了代码,收到了消息但没有显示通知

标签: android kotlin broadcastreceiver android-messaging


【解决方案1】:

您还没有添加 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())
    }

【讨论】:

    猜你喜欢
    • 2016-12-22
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多