• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Android Service 和多个 Activity 交互

用户头像
it1352
帮助1

问题说明

我正在尝试重构/重新设计一个 Android 应用.目前,我有一个创建 DataThread 的 UI 活动(Activity 1).该线程负责网络 I/O 并通过 handler 与 UI 活动交互(提供数据).

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 屏幕) - Activity 2.Activity 1 仍然是主要活动.Activity 2 将在用户点击 Activity 1 上的按钮时被调用.Activity 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 Service (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?

欢迎任何其他想法吗?

提前致谢.

正确答案

#1

我通常从 Application 类绑定我的服务,并有某种控制器类(我猜就像一个中介"......不知道所有这些模式如何被命名)作用域在处理服务和任何活动 Activity 之间通信的应用程序中.

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.

这将涉及编写您自己的 Application 类并告诉 Manifest 使用这个类.我在之前的帖子中详细介绍了这个过程:

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:

更高效的更新方式来自服务的用户界面而不是意图?

您可以通过在 onResume 中向 Application 类发送对自身的引用来跟踪当前活动"活动(也在上面的示例中进行了解释).这可以通过从公共基类派生您的活动来实现,该基类具有获取您的应用程序类的方法(从 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.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfieeg
系列文章
更多 icon
同类精品
更多 icon
继续加载