从 Activity 向服务发送消息,反之亦然

Send message from Activity to Service and vice versa

我以前从未使用过服务,但我看了很多 post 和教程,但我一直不太明白它是如何工作的。

所以我需要的是独立于应用程序生命周期在后台运行的东西(如服务),以异步接收和执行请求。 更详细地说,我希望这是一个下载队列。 如果用户请求下载,我计划通过启动服务来做到这一点。如果在第一个下载未完成时请求另一个下载,则该服务会将其放入队列中。该服务定期发送消息,以便 UI 得到更新。用户还可以暂停或取消下载(因此 activity 必须能够向服务发送消息)。

我知道如何下载东西,我想我知道如何启动该服务,但我不知道如何向该服务发送消息。
对于发给 Activity 的消息,我会这样做:

private void sendUpdateMessage(Bundle data) {
    Intent intent = new Intent("DownloadUpdate");
    intent.putExtra("data", data);
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

对于服务的消息,我想必须有某种绑定(我不太了解)。我找到了这个Communication between Activity and Service or this https://developer.android.com/reference/android/app/Service.html#remote-messenger-service-sample,但这看起来很复杂,很遗憾我不明白。

如果有人能简单说明如何在 Activity 和服务之间进行通信,那就太好了。
(同样,我知道在 Whosebug 上有关于此主题的 post,但出于某种原因我不明白如何正确地做到这一点)

我找到了一个非常有用的页面,其中包含很好的示例:
Effective communication between Service and Activity

三种可能的方式:

  • 广播和广播接收器

    The simplest solution uses Broadcasts and BroadcastReceivers. However, this method has the following disadvantages:
    The message sender does not know who will receive the data (it broadcasts the message). Broadcasts consume a lot of bandwidth and are not suited for high traffic.

  • 活页夹

    For Activities and Services used in one application the “Binder” solution is recommended. After binding with the service, the Binder will allow the activity (or other class bound to the service) to call any public method of the service.

  • 信使

    The recommended method of communication between Activities and Services for different applications’ Inter-Process Communication (IPC) is by using Messengers. In this case, the service defines a handler for different incoming messages. This handler is then used in Messenger for transferring data via messages.
    To get bi-directional communication, the activity also has to register a Messenger and Handler. This Messenger is passed to the service in one of messages. Without this the service wouldn’t know to who it should respond.

对于我的项目,我选择了最后一个。