Best Practices for developing an Activity with a background Service

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-10 18:27:04

问题


My Application has an Activity for the UI and a Service for background polling fun. Seems like standard fare.

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

  2. 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?

  3. Regarding communication between the two:

-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?

-It seems like I don't even need to bother with AIDL - the two could just have weak references to each other at the Application scope as well - and they can call methods on each other that way? Or should they pub/sub each other with some kind of Observer Pattern or BroadcastListener thing?


回答1:


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

Yes.

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

IMHO, no.

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

Yes.

Can you put 2 applications into one manifest somehow?

From a pure XML standpoint, there is room in the manifest for more than one <application> element. However, AFAIK, only one is supported.

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?

For very quick things, yes. However, bear in mind that your service may get shut down (by Android, by user, etc.), after which your process may get terminated, and your Application object goes poof. I'd use this for light caching only.

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

Correct -- that is only needed for inter-process service binding.

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

I wouldn't do that in a million years. Please use the platform responsibly. There are plenty of ways for activities and services to communicate yet remain loosely coupled (or, in the case of the local binding pattern, tightly-coupled in an Android-aware fashion).

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

Something along those lines would be preferable. While the activity and the service may be co-resident in the same process at the same time, they are not designed to be directly linked to one another.



来源:https://stackoverflow.com/questions/4904863/best-practices-for-developing-an-activity-with-a-background-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!