【问题标题】:Android Best-Way to communicate with a Foreground ServiceAndroid 与前台服务通信的最佳方式
【发布时间】:2016-10-28 21:49:57
【问题描述】:

我对安卓有点陌生。我想知道如何与前台启动的服务进行通信。

所以,我得到了一个带有通知的前台服务。 此通知有一个 (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
        }
}

所以我的问题是: BroadcastReceiver 是最好的方法吗? 如果是:我如何与服务通信以在广播接收器中调用 stopForeground?

提前感谢您的回复。

Same question like mien... 但我想知道广播接收器之外的其他解决方案。谢谢

【问题讨论】:

    标签: android service foreground


    【解决方案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(我无法附加到通知),以便与我的服务轻松通信或与我的服务本身进行自我调用。
    【解决方案2】:

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

    假设您正在使用通知启动服务,您可以在 Intent 中放置命令来告诉服务自行停止。 Service#onStartCommand 将在具有新 Intent 的服务上调用。该服务检查关闭调用并在完成时调用stopSelf()

    基本上,这样做的原因是因为只能启动一个服务。以后每次尝试启动服务都会将意图发送到Service#onStartCommand,但不会重新启动Service。因此,这是一种您可以通过绑定之外的方式向服务发送命令的方式。此外,它方式比使用广播更干净。

    【讨论】:

    • 感谢@DeeV onDelete 调用对我来说非常有用!
    猜你喜欢
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    相关资源
    最近更新 更多