【问题标题】:How to invoke a method on a foreground service by clicking on a notification action?如何通过单击通知操作来调用前台服务上的方法?
【发布时间】: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


【解决方案1】:

定义一个常数:

private const val EXTRA_STOP = "stop";

然后为您的服务创建一个意图并添加一个额外的标志:

val intent = Intent(context, YourService::class.java);
intent.putExtra(EXTRA_STOP, true);

现在您可以创建一个待处理的意图作为您的处理程序:

val pendingIntent: PendingIntent = PendingIntent.getService(context, YOUR_REQUEST_CODE, intent, PendingIntent.FLAG_IMMUTABLE)

这个待处理的意图将触发您的服务上的onStartCommand 方法,您可以在其中检查是否设置了停止标志。

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    if (intent != null && intent.getBooleanExtra(EXTRA_STOP, false)) {
        stopAction()
    }
    ...
}

【讨论】:

    猜你喜欢
    • 2017-03-23
    • 2020-03-17
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多