Android的服务与多个活动互动多个、互动、Android

2023-09-12 04:22:04 作者:无聊也不聊

我试图重构/重新设计一个Android应用程序。目前,我已经1 UI活动(活动1 ),创建一个 DataThread 。该线程负责网络I / O和交互(提供数据)通过一个处理程序中的用户界面活性

I'm trying to refactor/redesign an Android app. Currently, I've one UI activity (Activity 1) that creates a DataThread. This thread is responsible for network I/O and interacts (provides data) with the UI activity via a handler.

现在,我想补充另一个活动(有视频了全新的UI屏幕) - 活动2 活动1 仍是主要的活动。 活动2 当用户点击活动1按钮将调用活动2 的数据还来自 DataThread

Now, I want to add another activity (a new UI screen with Video) - Activity 2. Activity 1 is still the main activity. Activity 2 will be invoked when the user clicks a button on Activity 1. Activity 2's data also comes from the DataThread.

我的想法是把逻辑我的 DataThread 一个Android 服务里 DataService的)。我的问题是 - 能比对活动的绑定的我的的DataService 在同一时间?有没有办法告诉服务提供数据只是一个特定的活动?

My idea is to put the logic of my DataThread inside an Android Service (DataService). My question is - can more than on activity bind to my DataService at the same time? Is there a way to tell the service to provide data to a specific activity only?

任何其他的想法,欢迎?

Any other ideas are welcome?

在此先感谢。

推荐答案

我通常从绑定应用程序类我的服务,并有某种控制器类(像调解员,我想...不知道如何使所有这些模式被命名)范围在处理服务之间的通信的应用程序,无论主动行动是。

I usually bind my service from the Application class and have some kind of controller class (like a "mediator" I guess...not sure how all these patterns are named) scoped in the application that handles communications between services and whatever the active Activity is.

这将涉及编写自己的应用程序类,并告诉舱单使用这一个。我在previous线程进入更多的细节,这个过程:

This would involve writing your own Application class and telling the Manifest to use this one. I went into more detail on this process in a previous thread:

http://stackoverflow.com/questions/2621395/more-efficient-way-of-updating-ui-from-service-than-intents/2622473#2622473

您可以通过发送应用程序类的引用,自己在onResume跟踪当前活动活动的(也是为例来解释以上)。这可以通过派生的活动从具有让你的应用程序类(从getApplicationContext铸造)的方式公共基类来完成,而在这个基类的onResume,发送自身的裁判申请。然后,你可以用你DataServiceController登记的名字的活动,例如,发送消息只有当它注册到控制器的电流活动接收他们。

You could keep track of the "currently active" Activity by sending the Application class a reference to itself in onResume (also explained in the example above). This can be accomplished by deriving your Activities from a common base class that has a way of getting your Application class (casting from getApplicationContext), and in this base class' onResume, send a ref of itself to the application. Then, you can register activities by name with your DataServiceController, for example, and send messages to the current Activity only if it's registered with the Controller to receive them.