android - 在前台服务的 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
)
但是,点击不会在服务内注册。由于应用程序的某些复杂性,我无法将其添加到清单中,这是唯一的方法。那么可能是什么问题。是旗帜还是别的什么。
解决方案
您正在设置yourpackage.YourService.ServiceNotificationReceiver
未在清单中注册的意图目标组件,系统将无法解析它并且不执行任何操作。
修改您的意图以仅针对您的应用程序包,然后您的接收器将能够匹配它:
playintent = Intent().setPackage(this.packageName).setAction(FOREGROUND_PLAY_PAUSE)
推荐阅读
- postgresql - Postgres 在不同的选择查询中出现“缺少 FROM 子句条目”错误
- angular - DockerInDocker 构建 Angular 应用程序失败 - 没有这样的文件或目录
- c - 为什么 FreeRTOS 在 osKernelStart 声明后执行“main's”代码?代码调试
- excel - 如何复制一组列并将它们放在VBA中的一组行中
- wordpress - 使用 WooCommerce Rest API 创建带有优惠券行的订单
- azure - terraform:仅将公共 IP 添加到一个 azure VM
- python - 如何使用多个 3D 数组训练回归模型?
- javascript - 根据 JavaScript 中的值设置 CSS 样式
- leaflet - 带有翻转坐标的传单 .png 图像地图?
- android - Drawable 在 Android Studio 的不同活动布局中表现不同