What is a service?
- A Service is a component that can perform long-running operations in the background and does not provide a user interface.
Should I use service only for above purpose?
- No, there is another purpose, if you want to share some functionality with other application, then use Service. Using binder IPC one can share functionalities through a service.
Will the service runs infinitely even if the component that has started has died?
- Yes, it will run indefinitely as long as no one calls stopservice(), or stopself().
- NOTE: this will hold true only if your service is derived from Service class. In case if you have derived from IntentService class, it will be killed immediately after finishing its tasks.
Service means a thread?
- No, a service by default runs in the main thread of process of apk, in which it was started.
So, Can I write any long running functionality in service?
- Yes, but if you feel that if that logic interrupts the main thread functionality then create a separate thread in that service and then write your functionality in that thread.
Can I update UI from that service thread?
- No, directly you can’t update UI [of main thread] from this worker thread[of service]. If you want to do so, use Handlers help from the service. Easiest way is to use AsyncTask instead of raw threads to update UI.
Why I cannot update UI from other thread?
- Because, Main[UI] thread will contain a looper which actually dispatches all the events related to all UI components in that process. So, if some other thread is trying to touch UI components of the UI thread then UI-thread’s looper will not tolerate it. So you have to handle it gracefully by using a mediator class known as Handler class. Using Handler class you can do Inter-thread communication.
How do I use a service?
- A service can essentially take two forms:
What is the life cycle of a service?
- Startservice() à onCreate() à onStartCommand() à onDestroy() [stopservice()]
- Bindservice() à onCreate() à onBind() à onUnbind [unbind()] à onDestroy()