简体   繁体   中英

How to create two cooperating but non-blocking services in Android?

I am confused about where Android services run. I know services marked 'remote' run in their own processes, but what about ordinary local services?

The reason I ask is I want two local services to cooperate but not be blocked by each other. So for example, Service1 manages a network connection and receives packets. On receipt of a packet, I need that service to hand-off the packet to Service2 that processes the information and takes some action, including possibly sending a return message. I need the receipt, hand-off and processing to happen asynchronously, so the network service can continue to receive packets whilst the application service processes them. How do I ensure this happens?

I know one solution is to broadcast Intents, but how do I include custom data objects (ie packets) in an Intent? I don't want to implement the parcelable interface (overkill for local services) but I really need to be able to hand-off complex data objects between the services.

Thanks

Everything in your manifest file that is defined to run in the same process also share the same main thread. This thread is also sometimes the UI thread if that process has activities running in it. So, if you have two local services and they are running in the same process they are going to share the same main executing thread. In order for them to both do work 'at the same time' (until multicore android devices exist all execution is sequential anyway) then your service handling the network connection is going to need to do that in a separate thread. Your other service will need another thread as well.

Your problem is commonly called the producer-consumer pattern. Here's a link quick example of an simple implementation using blocking queues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM