与前台服务通信的Android最佳方法

3
我是一个新手,想知道如何与前台启动的服务通信。
因此,我有一个带有通知的前台服务。 该通知有一个(X)按钮来停止服务。
服务具有静态广播接收器。
public static class NotificationStopButtonHandler extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context,"Close Clicked",Toast.LENGTH_SHORT).show();
            Log.i(LOG_TAG, "In Closed");

            // imposible to do context.stopForground(true) or
            // to call any other private coded by me
        }
}

我的问题是: 广播接收器是否是最好的方式? 如果是:我如何与服务通信以在广播接收器中调用stopForeground?
感谢您提前的回复。 和我一样的问题...但我想知道除了广播接收器之外还有哪些解决方案。谢谢
2个回答

1

与其使用广播,您可以使用带有 Intent 的 PendingIntent 告诉服务关闭。将 PendingIntent 分配给关闭按钮操作和/或在构建通知时分配给 notifications onDelete call

假设您正在使用通知启动服务,则可以将命令放入 Intent 中以告诉服务停止自身。服务将使用新 Intent 调用 Service#onStartCommand。服务检查关闭调用并在完成后调用 stopSelf()

基本上,这样做的原因是因为只能启动一个服务。每次尝试启动服务时,都会将 Intent 发送到 Service#onStartCommand,但不会重新启动 Service。因此,这是一种通过绑定以外的方式向服务发送命令的方法。而且比使用广播要简洁得多


感谢 @DeeV,onDelete 调用在我的情况下非常有用! - Joe

1

在您的通知中,您将会有一个用于 X 按钮的 PendingIntent。我假设您已经使用了该 PendingIntent 进行构建。

PendingIntent.getBroadcast(/* ... */);

相反,您可以为服务创建PendingIntent。

Intent intent = /* intent for starting your service */;
intent.putExtra("STOP_FOREGROUND", true);
PendingIntent.getService(context, requestCode, intent, flags);

在您传递给PendingIntent的意图中,您需要添加一个额外的(STOP_FOREGROUND)。当触发此意图时,您的服务将在onStartCommand()中调用。在这里,您检查意图,如果它包含您的额外信息,那么您就知道应该调用stopForeground。

你好@Francesc,首先感谢你的回答。这确实是一个完美运作的解决方案之一。我一直有点保留不使用它,因为它进入了OnStartCommand。对我来说,就像每次你做getService..你想要启动它一样。但看起来这是最好的方法。与广播接收器不同,PendingIntent我想是“本地”的,只与我的应用程序通信。此外,我还实现了一个LocalBroadcastReceiver(无法附加到通知),以便轻松地与我的服务通信或自我调用我的服务本身。 - Joe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接