在前台服务的 onCreate() 中添加的广播接收器不起作用
Broadcast receiver added inside onCreate() of foreground service not working
服务内部的广播接收器class
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
)
但是点击没有在服务中注册。由于应用程序的某些复杂性,我无法将其添加到清单中,这是唯一的方法。那么可能是什么问题。是旗帜还是别的什么。
您正在将意图目标组件设置为 yourpackage.YourService.ServiceNotificationReceiver
,但未在清单中注册,系统将无法解析它并且不会执行任何操作。
修改您的意图以仅定位您的应用程序包,然后您的接收者将能够匹配它:
playintent = Intent().setPackage(this.packageName).setAction(FOREGROUND_PLAY_PAUSE)
服务内部的广播接收器class
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
)
但是点击没有在服务中注册。由于应用程序的某些复杂性,我无法将其添加到清单中,这是唯一的方法。那么可能是什么问题。是旗帜还是别的什么。
您正在将意图目标组件设置为 yourpackage.YourService.ServiceNotificationReceiver
,但未在清单中注册,系统将无法解析它并且不会执行任何操作。
修改您的意图以仅定位您的应用程序包,然后您的接收者将能够匹配它:
playintent = Intent().setPackage(this.packageName).setAction(FOREGROUND_PLAY_PAUSE)