Thứ Năm, 12 tháng 12, 2013

Sự khác nhau giữa Service và IntentService

Service is a base class of service implementation. However, according to my understanding, it's not a best choice to begin with. Service class is run in the application's main thread which may reduce the application performance. Thus, IntentService, which is a direct subclass of Service is borned to make things easier. In my opinion, the main concern of IntentService class is about the thread, but there are also other differences out there.
Differences
  1. Service class uses the application's main thread, while IntentService creates a worker thread and uses that thread to run the service.
  2. IntentService creates a queue that passes one intent at a time to onHandleIntent(). Thus, implementing a multi-thread should be made by extending Service class directly.
  3. Service class needs a manual stop using stopSelf(). Meanwhile, IntentService automatically stops itself when there is no intent in queue. 
  4. IntentService implements onBind() that returns null. This means that the IntentService can not be bound by default.
  5. IntentService implements onStartCommand() that sends Intent to queue and to onHandleIntent().
In brief, there are only two things to do to use IntentService. Firstly, to implement the constructor. And secondly, to implement onHandleIntent(). For other callback methods, the super is needed to be called so that it can be tracked properly.