Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Service and Thread in Android? [duplicate]

Tags:

android

all I need to know is that when I can do some operation using an independent thread, why do I need Service. What is that, a Service can do but a Thread can't? I did go to through many of the posts but couldn't find a satisfactory answer.

like image 525
SAMD Avatar asked Feb 05 '12 05:02

SAMD


1 Answers

Service : is a component of android which performs long running operation in background, mostly with out having UI.

Thread : is a O.S level feature that allow you to do some operation in the background.

Though conceptually both looks similar there are some crucial differentiation.

1.Service - if it is destroyed while performing its job, in the middle by Android due to low memory scenario. Then android will make sure that it will restart your service, if you have returned START_STICKY or START_REDELIVER_INTENT from onStartCommand().

2.Thread - if it is destroyed by android in middle due to low memory, then android will not guarantee to restart it again. That means user lost his half work.

3.Service - is a component of android, so it has priority levels to be considered while destroying an application due to low memory.

4. Thread - is not a component of android, so android will not take thread priority into consideration while killing an application due to low memory.

I will try to explain this 3rd point.

Lets, say you have a requirement of connecting to internet from your activity. You can do it by using a service(with thread) or directly by creating a thread in activity. Consider the second scenario where you are connecting to internet in a thread. Then

i. What will happen if user closes the activity, while still thread is running in the background. Will that thread continue to run in back ground ? Answer is you can't really predict.

ii. Assume that in continuation for above scenario, even after killing activity your thread continued to do its intended operation. Then there is a low memory situation arises in your phone. Then this application will be the first susceptible app to be killed as there is no priority for this application.

So bottom line is: If you want to do some heavy background functionality then it is always better to have a service with thread. If you feel that that background functionality to be alive as long as your activity is alive, then go for activity with thread or activity with async task.

Hope it helps.

like image 130
user1923551 Avatar answered Nov 06 '22 05:11

user1923551