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
?
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.