Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>My rule of thumb is that an <code>AsyncTask</code> is for when I want to do something tied to single <code>Activity</code> and a <code>Service</code> is for when I want to do something that will carry on after the Activity which started it is in the background.</p> <p>So if I want to do a small bit of background processing in the <code>Activity</code> without tying up the UI I'll use an <code>AsyncTask</code>. I'll then use the default <code>Handler</code> from that <code>Activity</code> 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.</p> <p>If for example, I wanted to do a download which might take a while I'd use a <code>Service</code>. So if I went to another <code>Activity</code> in my application or another application entirely my <code>Service</code> 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 <a href="http://developer.android.com/intl/fr/guide/topics/ui/notifiers/notifications.html" rel="noreferrer">Status Bar Notification</a> once the download was complete, so the user could choose to return to my application whenever was convenient for them.</p> <p>What you'll find if you use an <code>AsyncTask</code> for a long-running process it may continue after you've navigated away from the <code>Activity</code> but:</p> <ul> <li>If the <code>Activity</code> is in the background when your processing is complete you may have problems when you try to update the UI with the results etc.</li> <li>A background <code>Activity</code> is far more likely to be killed by Android when it needs memory than a <code>Service</code>.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload