带有 EventBus 和启动服务的 Android MVP

标签 android unit-testing android-service android-mvp greenrobot-eventbus-3.0

上下文

我写了一个Android App播放单个媒体文件,其歌词显示在 Activity 中。 Activity 屏幕还有一个播放暂停切换按钮和一个使用拖动来前进/后退的搜索栏。 Activity 在其 onCreate() 方法中启动 Started Service。

我正在尝试对应用进行分层以确认 MVP 设计模式。我正在寻找适合这种情况的示例代码作为指导。非常感谢您的帮助。

我想学的东西

  1. 如果像我这样,Activity 和 Started Service 使用 EventBus 进行双向通信,那么 EventBus 监听器的代码在哪里? Presenter 在这方面没有任何作用吗?
  2. 如何针对 EventBus 相关代码测试代码 - 单元测试和集成测试?
  3. Activity 中有哪些代码?服务中有什么? Presenter 与 Activity 和 Service 的契约(Contract)是什么样的?最后,这个 Presenter 的实现情况如何?
  4. 在 MVP 的情况下,您如何管理 MenuOptions 点击事件的代码?

任何对 Github/Bitbucket 中现有代码存储库的引用都非常感谢,如果详细的解释对您不利。提前致谢。

最佳答案

我个人不会使用 EventBus 来实现它。无论如何,这是我对您问题的回答。

  1. In case like mine where the Activity and the Started Service have two-way communications using EventBus, where does the code for EventBus listener lie in? Is Presenter not having any role in this?

是的,Presenter 注册到 EventBus 以监听传入的事件并告诉 View 要显示什么。反过来,如果用户点击播放/暂停按钮,则此事件将通过 Presenter 传递给您的服务(可能通过 EventBus。可能通过传递给服务的 android intents,无论如何......但是传递此事件,即通过eventbus 发生在 Presenter 中)。所以 Activity 不直接与 Service 通信。它是您的 View ( Activity )的呈现器,它在 View ( Activity )和播放服务之间进行调解。

  1. How is the code tested for EventBus related code - both unit and integrating testing?

您不必测试 EventBus 本身。它已经由图书馆的作者测试过。因此,将 EventBus 作为构造函数参数传递给您的演示者,在进行单元测试时,您可以将模拟的 EventBus 传递给您的演示者,以检查您的演示者是否正确注册/注销,并且您可以启动一些事件以查看演示者是否正确处理了事件并且调用 View 上的预期方法(模拟 View ),反之亦然,以将事件(如播放/暂停)发送到服务。

  1. What code comes in Activity? What comes in Service? And What does the Presenter contract with Activity and Service look like? Lastly, how does the implementation of this presenter look like?

请参阅 1 的答案。Activity 仅显示 UI 小部件。将点击事件转发给演示者。 Presenter 与 Service 通信(例如通过 EventBus)。反过来:如果您的服务更改状态(如到达音轨结尾),那么它将通知 Presenter(即通过 EventBus)音频播放已完成,Presenter 告诉 View 相应地显示 UI。

  1. How do you manage code for MenuOptions click events in the case of MVP?

如 1 和 3 中所述。如果它要更改您的业务逻辑的状态(即播放/暂停),它会从您的 View ( Activity )通过 Presenter 向下“下沉”到业务逻辑(即回放服务) ).

关于带有 EventBus 和启动服务的 Android MVP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44662617/

相关文章:

android - 当引用的 View 在 ConstraintLayout 中消失时保持边距

c# - 单元测试时在方法内部创建模拟对象

android - 从网络服务读取数据、解析数据并将其插入 SQLite 数据库的推荐方式/顺序

android - 是什么导致了这个 IllegalArgumentException : Service not Registered?

android - 谷歌应用商店 : how to change "Offered By" for an app

android - 当使用 ImagePicker 在 android 中选择多个图像时,ionic 应用程序关闭

javascript - 在android中使用phonegap调用电话号码

scala - specs2 scala 测试中 OneAppPerSuite 的替代方案

unit-testing - 单元测试-定义

android - JobScheduler 可以执行前台服务吗?