Search code examples
androidserviceandroid-asynctaskbackground-process

Android - Best way to do asynchronous tasks


I have a very intensive task, where I parse around 100 json files stored in assets and create a tree structure from that.. Then i update the UI based on resulted tree.l

Currently, I am using AsyncTask to do this job.

But, I am looking for better, efficient and clean way to do this. Any libraries or any other in-built functionality which i should use ?


Solution

  • I would go with an IntentService here. It already provides a background thread and it will stop itself once it's done. If you need to update the UI after that, you can use a Handler or a BroadcastReceiver.

    EDIT

    You can still use an AsyncTask but still, start it from a Service. AsyncTask is just a wrapper around java thread, it's not an Android component. You have to start it from some context, in this case it's either Activity or Service.

    If you start it from Activity then your long-running operation will depend on the UI which in most cases will cause a memory leak. Service is a background component which runs independently from the UI. Also, Service will increase your app's process priority so that it less likely to be killed by Android when the system is running on low memory.

    If you use IntentService, you don't need an AsyncTask anymore, it runs on the backround thread already. If you want to go with a regular Service, you will need to implement background execution on your own. Via java thread or async task for example.