Reputation: 1365
This is very basic question but I am unable to figure it out because as I read that Service runs on main thread. So why do we need to create a Service? and because for intense CPU task we need to create Async task or thread in Service then why don't we create them in activity or application class?
I wanted to create a service which will continuously perform a set of task when it is started. I can't find any method in Service which will run in loop. Is there is such method? or do I have to create a thread in service to set a loop?
Upvotes: 1
Views: 545
Reputation: 16043
why don't we create them in activity or application class?
You can, but it depends of task you want to accomplish. The main characteristic of a Service
is that it runs in background, decoupled from Activity life cycle.
Imagine the following situation, you are working on a Media Player application and would like to let the users play music, even when they exit the application, in background.
Now, if you put the media player logic in Activity, then when users will leave the app, the music will stop, as this will terminate the media player. That is not good, we want the music to continue playing in background when they leave the app. Well, in order to achieve this, you should put the playing logic in a Service
.
Also, take a look over IntentService class, which provides its own worker thread, so you shouldn't define your own.
I can't find any method in Service which will run in loop. Is there is such method?
No, there isn't. You either start the service again, or, create a loop inside the service.
Upvotes: 2