android - 使用后台服务开发 Activity 的最佳实践

标签 android manifest background-process alarmmanager

我的应用程序有一个用于 UI 的 Activity 和一个用于后台轮询的服务。看起来像标准票价。

  1. AlarmManager 是否可以在不调用 Activity OnCreate 的情况下触发 Service Intent?

  2. 将 Activity 和服务放入不同的应用程序有什么好处吗?这会创建 2 个 apk 并使其无法作为一个应用程序放入市场吗?你能以某种方式将 2 个应用程序放入一个 list 中吗?

  3. 关于两者之间的沟通:

-如果 Activity 和 Service 是同一应用程序的一部分 - 我不能只在应用程序范围内存储公共(public)对象(如用户对象)以供 2 共享吗?

- 似乎我什至不需要为 AIDL 操心——这两者也可能只是在应用程序范围内彼此有弱引用——他们可以那样互相调用方法吗?或者他们应该用某种观察者模式或 BroadcastListener 东西互相发布/订阅?

最佳答案

Can AlarmManager trigger the Service Intent without Activity OnCreate being called?

是的。

Is there any benefit to putting the Activity & Service into different Applications?

恕我直言,不。

Would this create 2 apk's and make it impossible to put into Market as one app?

是的。

Can you put 2 applications into one manifest somehow?

从纯 XML 的角度来看, list 中有多个空间 <application>元素。但是,据我所知,仅支持一个。

If Activity & Service are part of the same Application - can't I just store common objects (like User object) at the Application scope for the 2 to share?

对于非常快速的事情,是的。但是,请记住,您的服务可能会被关闭(由 Android、用户等),之后您的进程可能会终止,并且您的 Application对象变得。我只会将其用于轻度缓存。

It seems like I don't even need to bother with AIDL

正确——只有进程间服务绑定(bind)才需要。

the two could just have weak references to each other at the Application scope as well

我不会在一百万年内这样做。请负责任地使用平台。 Activity 和服务可以通过多种方式进行通信,但仍保持松散耦合(或者,在本地绑定(bind)模式的情况下,以 Android 感知方式紧密耦合)。

Or should they pub/sub each other with some kind of Observer Pattern or BroadcastListener thing?

沿着这些思路的东西会更可取。虽然 Activity 和服务可能同时共存于同一进程中,但它们并非设计为彼此直接链接。

关于android - 使用后台服务开发 Activity 的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4904863/

相关文章:

选择图像时android应用程序退出

java - 如何使用 2 个键在 HashMap 或 ArrayList 上获取或设置值

android - 在 android studio canary -2 中找不到版本代码

java - 如何从项目中删除jar文件?

java - 我可以在 ThreadPool 中运行后台任务吗?

ios - 启用 iOS 通知以激活后台服务

android - 将 Android 应用排除在待机桶之外

android - Android 的图像/文本识别

php - MYSQL 文本看起来很奇怪

android - uses-permission-sdk-23 和 uses-permission 之间的区别?