首页 > 解决方案 > 在前台服务的 onCreate() 中添加的广播接收器不起作用

问题描述

服务内的广播接收器类

  inner class ServiceNotificationReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent!!.action
            Util.log("action from foreground services")
            when (action) {
                FOREGROUND_NEXT -> {
                    next()
                }
                FOREGROUND_PREVIOUS -> {
                    prevoius()
                }
                FOREGROUND_PLAY_PAUSE -> {
                    if (exoPlayer.isPlaying) {
                        pause()
                    } else {
                        play()
                    }
                }
                FOREGROUND_STOP -> {
                    stopSelf()
                }
            }
        }

    }

我像这样在服务的 onCreate() 中注册它

  serviceNotificationListener = ServiceNotificationReceiver()

        val intentfliter = IntentFilter().apply {
            addAction(FOREGROUND_PLAY_PAUSE)
            addAction(FOREGROUND_PREVIOUS)
            addAction(FOREGROUND_NEXT)
            addAction(FOREGROUND_STOP)
        }
        this.registerReceiver(serviceNotificationListener, intentfliter)

待定意图

playintent = Intent(this, ServiceNotificationReceiver::class.java).setAction(
        FOREGROUND_PLAY_PAUSE
    )

    playpendingIntent =
        PendingIntent.getBroadcast(this, 0, playintent, PendingIntent.FLAG_UPDATE_CURRENT)

我将它添加为通知生成器中的一个动作,就像这样

  addAction(
                com.google.android.exoplayer2.R.drawable.exo_icon_previous,
                "Previous",
                previouspendingIntent
            )

但是,点击不会在服务内注册。由于应用程序的某些复杂性,我无法将其添加到清单中,这是唯一的方法。那么可能是什么问题。是旗帜还是别的什么。

标签: androidservicebroadcastreceiver

解决方案


您正在设置yourpackage.YourService.ServiceNotificationReceiver未在清单中注册的意图目标组件,系统将无法解析它并且不执行任何操作。

修改您的意图以仅针对您的应用程序包,然后您的接收器将能够匹配它:

playintent = Intent().setPackage(this.packageName).setAction(FOREGROUND_PLAY_PAUSE)

推荐阅读