【发布时间】:2022-08-13 20:47:43
【问题描述】:
我有前台服务。它在后台执行一些异步工作,并定期发出通知,询问用户是否应该停止工作。
通知有一个按钮\“是的,请\”当点击它必须调用stopAction 方法。
下面的代码是我卡住的地方。我可能很遥远,这无法完成。有什么建议吗?
主服务.kt
...
override fun onCreate() {
subscribeToStopRequest()
}
private fun subscribeToStopRequest () {
var eventService = EventService { stopAction() }
val filter = IntentFilter().apply {
addAction(\"${packageName}.stop_request\")
}
registerReceiver(eventService, filter)
}
private fun stopAction () {
...
}
private fun showOfferNotification () {
val intent = Intent(this, EventService::class.java)
val pendingIntent: PendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
var notification = NotificationCompat.Builder(this, state.notificationChannelId)
.setContentTitle(\"Want to stop?\")
.addAction(R.drawable.stop_icon, \"Yes, please\", pendingIntent)
.build()
with(NotificationManagerCompat.from(this)) {
notify(1, notification)
}
}
事件接收器
class EventService(val cb: () -> Unit): BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
cb()
}
}
-
创建
EventService作为MainService的内部类,然后您可以直接调用外部类的任何方法。不确定这是否是您要问的..
标签: android kotlin android-notifications