Bear
Bear

Reputation: 5152

onStartCommand with intent action vs bound service

If the way I interact with service is single directional (that is only call service to do something without asking for result). What is the difference between these two approaches:

  1. startService(intent) and onStartCommand do task depend on intent.getAction
  2. bind the service and send message to the service using Messenger. So that service do task based on the message.

Here is one difference I can thought ( I am not sure):
For approach 1, we need to create the service every time we call startService, so the overloading is we need to create the service every time unless use START_STICKY.

Upvotes: 3

Views: 663

Answers (1)

G. Blake Meike
G. Blake Meike

Reputation: 6715

There are several differences but the most significant is thread management.

IntentService If you use an Intent service, onHandleIntent is called in a single daemon thread. Each new call to startService will appear as an in-order, queued call to onHandleIntent. The result is simple, well behaved, in-order execution of calls, on that daemon thread. Btw, the service will not stop itself until the queue is empty: no need to "recreate"

Bound Service in same App There are, actually, two cases for a bound service. If it is running in your process, the service will run on the UI thread. If you need stuff run off the UI thread, you will have to build your own thread (probably a Looper) and, thus, talk to it with a Messenger. The result is more flexible (# of threads, queueing order, etc. is up to you) but very similar to the IntentService.

Bound Service in another App If the Bound service belongs to a different application, your calls to it are run on one of several Binder threads. You don't need to manage those threads, they are supplied by the framework. They can, however, execute your calls out of order.

Upvotes: 2

Related Questions