如何在服务和活动(和它的子活动)之间的处理IPC?它的、如何在、IPC

由网友(施主你的节操掉了)分享简介:通信可以通过Messenger的管理或AIDL 的:它是足够的活性结合到服务Communication between two different processes (a service and an activity) in Android can be managed via Messenger or AIDL...

通信可以通过Messenger的管理或AIDL 的:它是足够的活性结合到服务

Communication between two different processes (a service and an activity) in Android can be managed via Messenger or AIDL: it is sufficient that an activity binds to a service.

不过,会发生什么? 从当主活动开始一个子活动的那一刻,我想的通信重定向到子活动;同样,当子活动被破坏,我想在通信被重定向回到主活动,等等。

However, what happens if this activity has one or more sub-activity? From the moment when the main activity starts a sub-activity, I would like the communication to be redirected to the sub-activity; similarly, when the sub-activity is destroyed, I would like the communication is redirected back to the main activity, etc..

例1:

为MyService< --- IPC - > MainActivity MainActivity启动子活动,然后为MyService< --- IPC - >子活动 子活动被破坏,然后为MyService< --- IPC - > MainActivity

例2:

为MyService< --- IPC - > MainActivity MainActivity推出FirstSubActivity,然后为MyService< --- IPC - > FirstSubActivity FirstSubActivity推出SecondSubActivity,然后为MyService< --- IPC - > SecondSubActivity SecondSubActivity被破坏,然后为MyService< --- IPC - > FirstSubActivity FirstSubActivity被破坏,然后为MyService< --- IPC - > MainActivity

如何处理这些情况?

推荐答案

您想拥有,负责绑定到服务,并持有到连接一个单一的实体,你需要一个实体不被活动实例。试试这个:

You want to have a single entity that is responsible for binding to the service and holding on to the connection and you need that entity NOT to be an Activity instance. Try this:

创建子类活动的基类(BaseActivity) 源于BaseActivity所有的活动 管理应用程序和使用方法BaseActivity您的服务之间的连接。 BaseActivity将需要具有静态(类)保持连接到服务跟踪变量和处理绑定到服务,并关闭它,当你用它做。 确保使用应用程序上下文(不活动的情况下),当绑定的服务,让操作系统不会杀的连接时,该活动被销毁的服务。

在这种方式,您不必担心创建拆了不同的活动和服务之间的连接。只有过你的一个完整的应用程序(所有活动)和您的服务之间的连接。

In this way you don't have to worry about creating and tearing down connections between the different activities and your service. There is only ever one connection between your entire application (all the activities) and your service.

我意识到,我没有解释所有的血淋淋的细节,但希望你得到的基本思路。

I realize that I haven't explained all the gory details, but hopefully you get the basic idea.

阅读全文

相关推荐

最新文章