Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use a Service or AsyncTask or Handler?

Can someone tell me the TRUE difference?

like image 519
TIMEX Avatar asked Feb 18 '10 01:02

TIMEX


People also ask

What is difference between service and AsyncTask?

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.

What is the difference between handler vs AsyncTask vs thread?

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.

Why do we use AsyncTask?

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.

What is the difference between service and thread?

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.


1 Answers

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:

  • If the 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.
  • A background Activity is far more likely to be killed by Android when it needs memory than a Service.
like image 183
Dave Webb Avatar answered Oct 04 '22 09:10

Dave Webb