android - 长时间运行 Android 'service'

标签 android multithreading service

我有一个 Android 应用程序,其中 Activity 触发在后台运行的长时间运行的操作。这些操作在完成时与 Activity 交互。我正在开发一个处理 Activity/Long-Running-Task 耦合的组件,负责销毁和重新创建 Activity 。

现在该组件是作为 Android 服务实现的。 Activity 调用 bindService 并使用生成的 IBinder 来启动和跟踪任务。我决定不使用 startService,因为我更喜欢通过 Java 接口(interface)获得更丰富的 API。

现在是问题。 Activity A 启动,绑定(bind)到服务并调用 serviceApi.runTask(...)。然后 Activity A 被销毁(例如,因为用户翻转手机)并重新创建为 Activity A'。 A' 然后再次绑定(bind)到该服务,宣布它的存在并且一切都应该正常运行。

除了我的服务被销毁。当 Activity A 被销毁时,它与服务解除绑定(bind)。 Android 看到没有更多的客户端,并终止了该服务。创建 Activity A' 时,将再次创建该服务,而我将失去旧服务的所有内容。

我能看到的唯一解决方案是为该服务使用单例。然后它实际上不必是 Android 服务,只是每个人都可以访问的实例。这在 Android 中不受欢迎吗?有没有更好的设计来解决这个问题?


已编辑:即使我调用 startService 然后绑定(bind)到它,也无法保证只要应用程序正在运行服务实例就会存在。如果资源不足,Android 可以终止粘性服务。终止该服务将导致应用程序出现故障,我不能这样。

最佳答案

Even if I call startService and then bind to it, nothing guarantees that the service instance will exist as long as the application is running.

正确。

Android can kill sticky services if resources are low.

也正确。所有“粘性”意味着 Android 可能会重启服务。

Killing the service will cause the application to malfunction, and I can't have that.

不可能创建保证永远运行的服务。对于初学者来说,用户可以随时摆脱你的服务,因为用户讨厌那些拥有永远运行的无意义服务的开发人员。只有在极少数情况下才需要编写永久服务;否则,这只是草率的编程。

The only solution I can see is using a singleton for the service. And then it doesn't really have to be an Android service, just an instance that's accessible to everyone. Is that frowned upon in Android?

单例(又名,静态数据成员)将在进程终止时消失。该过程最终将终止,特别是如果没有 Activity 服务并且您的任何 Activity 都不在前台..

关于android - 长时间运行 Android 'service',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8113701/

相关文章:

mysql - RedmineMySQL 未启动

grails - 如何使用 Grails 服务层实现多态行为

android - 单次触摸后如何启用拖动标记(Android Map Api v2)?

java - 使用 Volley 和 Gson : Parse item and items list

java - 如何创建闪光灯和频闪效果。需要帮助来修复频闪效应

Android Looper 和 Thread 似乎不起作用

c# - WPF:处理另一个线程上的 touchmove 事件

multithreading - 使用 win32 线程的 C++/CLI 引用类

java - 为什么我的代码运行在主线程上?

android - 禁用演示文稿的隐藏(辅助屏幕)