Can someone tell me the TRUE difference?
service is like activity long time consuming task but Async task allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.
Using Handlers you have the advantage of MessagingQueues , so if you want to schedule messages or update multiple UI elements or have repeating tasks. AsyncTask are similar, in fact, they make use of Handler , but doesn't run in the UI thread, so it's good for fetching data, for instance fetching web services.
Android AsyncTask is an abstract class provided by Android which gives us the liberty to perform heavy tasks in the background and keep the UI thread light thus making the application more responsive. Android application runs on a single thread when launched.
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.
My rule of thumb is that an AsyncTask
is for when I want to do something tied to single Activity
and a Service
is for when I want to do something that will carry on after the Activity which started it is in the background.
So if I want to do a small bit of background processing in the Activity
without tying up the UI I'll use an AsyncTask
. I'll then use the default Handler
from that Activity
to pass messages back to ensure updates happen on the main thread. Processing the updates on the main thread has two benefits: UI updates happen correctly and you don't have to worry so much about synchronisation problems.
If for example, I wanted to do a download which might take a while I'd use a Service
. So if I went to another Activity
in my application or another application entirely my Service
could keep running and keep downloading the file so it would be ready when I returned to my application. In this case I'd probably use a Status Bar Notification once the download was complete, so the user could choose to return to my application whenever was convenient for them.
What you'll find if you use an AsyncTask
for a long-running process it may continue after you've navigated away from the Activity
but:
Activity
is in the background when your processing is complete you may have problems when you try to update the UI with the results etc.Activity
is far more likely to be killed by Android when it needs memory than a Service
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With