Should I use AsyncTask or IntentService for my application?

28,752

Solution 1

You should use an AsyncTask for short repetitive tasks that are tightly bound to an activity, like what you're currently trying to do. IntentService are more geared towards scheduled tasks (repetitive or not) that should run on the background, independent of your activity.

Solution 2

They can be used very differently for different purposes.

AsyncTask is a handy threading utility that can be used if you need to constantly tell the user something or periodically perform operations on the main thread. It offers a lot of fine-grain control, and because of it's nature is very easy to work with in the Activity whereas an IntentService generally requires using the BroadcastReceiver or IBinder framework.

IntentService can be used very much like an AsyncTask, but it's purpose is meant for background downloading, uploading, or other blocking operations that don't need user interaction or main thread. For example, if you want to download and cache maps, you may want to call an IntentService so the user doesn't have to be looking at the app for it to download. Likewise, if you're sending data to your server, an IntentService is extremely helpful in this regard because you can start and forget. The user can, say, type a comment in your app then press "send". "Send" will launch the IntentService which gets the comment and send it off in to your server on a background thread. The user could press "send" and leave the app immediately and the comment will, eventually, still reach your servers (assuming no errors of course). If you did this with an AsyncTask in your Activity on the other hand, the system could kill off your process in the middle of your exchange and it may-or-may not go through.

Generally speaking, neither are meant for long running applications. They're meant for short, one-off operations. They could be used for permanent, or long-running actions but it's not recommended.

Solution 3

AsyncTask doesn't play well with configuration changes or other things that restart the Activity.

IntentService is good for a something that should always be available, regardless of how long it takes to do its work. I prefer IntentService in most cases because AsyncTask is so much more dependent on Activity state.

Some notes:

  • AsyncTask is best for quick tasks that should go right back to the UI, but it can be used in a variety of situations.
  • The statement "periodically perform operations on the main thread" is vague. AsyncTask spawns a new background thread that is different from the main thread, and does its work on the new thread. Thus the name AsyncTask.
  • An IntentService doesn't require "manipulating" the BroadcastReceiver framework. All you need to do is send a local broadcast Intent, and detect it in your Activity. Whether this is harder to do than an AsyncTask, I don't know.
  • IntentService is meant to do long-running tasks, which it does in the background.
  • AsyncTaskLoader is OK to use, but it's meant to be the base class for CursorLoader, etc. If you want to refresh "nearby" trails when users move to a new location, an IntentService is probably better.

Don't forget to check for connectivity before trying to update location.

Solution 4

AsyncTasks are very tightly bound to Activitys and can often cause leaked window errors if you navigate away from the Activity that created the AsyncTask. But they are great for showing a ProgressBar because you can quickly update the progress percentage.

IntentServices are cleaner and safer. They are more difficult to implement when you are a beginner Android developer, but once you learn how to start them and handle them you will probably never go back to AsyncTasks!

IntentServices also allow for a more modular design in your app. I typically create a separate class for all my IntentServices, but for AsyncTasks I create them as an Activity inner class. If I were to separate out an AsyncTask from an Activity, I would have to pass in the Activity Context and View objects in the AsyncTask constructor which can be messy.

Solution 5

As mentioned above AsyncTask will solve your problem.

But Keep in mind that AsyncTask has an important weakness: it doesn't handle well Activity "refresh" (eg during rotation). It may be a problem if, e.g., user rotate the phone while your AsyncTask is still loading stuff. If this is indeed a problem for you I recommend AsyncTaskLoader:

http://developer.android.com/reference/android/content/AsyncTaskLoader.html

Share:
28,752
Johnathan Au
Author by

Johnathan Au

Updated on May 22, 2020

Comments

  • Johnathan Au
    Johnathan Au about 4 years

    I have been reading around on internet connectivity with Android and noticed there are different ways to handle this i.e. AsyncTask and IntentService. However, I'm still not sure which one to use. My application is basically a location/trails finder with Google Maps. My internet connectivity will be used to find the nearest trails within a certain radius of the map. So, every time a user moves or swipes the map to a new location then it will update with the nearest trails. It will also add a new trail, and allow the user to rate a trail.

    Will AsyncTask suffice for this or should I use IntentService?

  • Johnathan Au
    Johnathan Au about 11 years
    Thank you for your answer. Can you give me an example of a task that would use IntentService?
  • ebarrenechea
    ebarrenechea about 11 years
    Suppose you save trails for a given region on your app (like "favourites" or similar). If you want to keep them up-to-date then just set up an IntentService that would run every day and check for changes on those regions.
  • Johnathan Au
    Johnathan Au about 11 years
    Ah, I see. So I guess it's like Facebook or Gmail notifications on our phones?
  • ebarrenechea
    ebarrenechea about 11 years
    Pretty much, although I'm fairly certain those use push notifications, which are a different thing altogether. It would be like the email application with IMAP/POP3 that checks for emails every x minutes.
  • roiberg
    roiberg about 11 years
    What should be used for the long-running operations than?
  • DeeV
    DeeV about 11 years
    A generic Java Thread if it's blocking. You can put it in an Activity or Service depending on the need. Control the lifecycle using the lifecycle methods to ensure they don't run when they're not supposed to.
  • Kanwal Sarwara
    Kanwal Sarwara about 11 years
    This is wrong information, IntenetService cannot run independently of your application, Service can.
  • MSaudi
    MSaudi about 10 years
    @Sarwara , What do you mean ?
  • Kanwal Sarwara
    Kanwal Sarwara about 10 years
    comment says: "IntentService are more geared towards scheduled tasks (repetitive or not) that should run on the background, independent of your activity." But IntentService cannot run if your application is not running, If you want something to run even when application is off, you need Service, not IntentService.
  • Jim G.
    Jim G. about 10 years
    -1: ...An IntentService generally requires manipulating the BroadcastReceiver framework. No, it doesn't. Please see @Joe Malin's answer: stackoverflow.com/a/15168625/109941?
  • DeeV
    DeeV about 10 years
    That was meant in comparison to Asynctask which would use callbacks. You don't have to use BroadcastReceivers for anything, but that is an approach if you want it to report back to the Activity. Another approach would be binding since it is at it's core a normal Service.
  • Glenn Bech
    Glenn Bech almost 9 years
    I do this in some apps: When the app is started I launch an IntentService to update the local data if needed (time since last update , WIFI available etc). The Application always displays what is stored locally. When new data is available I use a LocalBroadcastManager to notify the application and it refreshes its views (mostly calls to notifyDataSetChanged on adapter) In this scenario, an IntentService is a lot better than an AsyncTask Whatever activity that is currently active when data is ready will be notified and can chose to act on the new data or not.
  • Paul Okeke
    Paul Okeke almost 9 years
    @Sarwara Please, and how can the activity get result , lets say i sent a message and i need to know if the message has been delivered or not?
  • Eslam Sameh Ahmed
    Eslam Sameh Ahmed almost 9 years
    AsyncTask used only for few seconds operations
  • ban-geoengineering
    ban-geoengineering over 8 years
    To overcome the messy problem, couldn't you add an inner Interface to your AsyncTask class. The interface would contain the callback method(s) for the activity to implement?
  • ban-geoengineering
    ban-geoengineering over 8 years
    You can use IntentService for long-running operations. I use it (correctly) for perpetual operations.
  • ban-geoengineering
    ban-geoengineering over 8 years
    Are you sure Loader should be used for server work? I've never heard of that before and I didn't see anything in the docs or tutorial you linked to that suggested that.
  • DeeV
    DeeV over 8 years
    @ban-geoengineering Wouldn't that mean you'd need a separate Service running for each operation rather than one Service that runs them in parallel?
  • ban-geoengineering
    ban-geoengineering over 8 years
    No sure, but as stated in the IntentService documentation: "All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time." developer.android.com/reference/android/app/IntentService.ht‌​ml
  • DeeV
    DeeV over 8 years
    @ban-geoengineering Right. So if you wanted to do two long-running processes, you'd need two running services. The same if you had 5, 8, 10 or more. Although I guess for most cases, it's not a big deal.