I am new to android development. Currently i am working on an application which will take a query from user, send the query to the server and will receive an XML response in return. Then it will process the xML response using XMLparser, will extract the answer from XML response and display answer to the user. Since all this processing takes some time, i want to show a progress dialog to the user for the processing time it takes.
I have gone through some ways of doing this like i can use AsyncTask, Handler or Runnable (java) threads. But as much I have read about all these, I have got confused which one to use. Please tell me which one is better to use for above mentioned scenario. And a simple way to implement the preferred one.
Thank You in advance.
From http://developer.android.com/reference/android/os/AsyncTask.html :
AsyncTask is designed for a use very similar to yours.
Runnable is only to run a block of code on another thread:
Handler is used more for Message Queuing. Your case doesn't seem to require messages being sent repeatedly.
Note that neither Runnable nor Handler talk about displaying the results back on the UI thread. That is where AsyncTask helps you more than either of these.
AsyncTask might be the choice,because it provides all necessary controls for starting up the async task, updating progress bar, etc.
But, the point is AsyncTask is the best solution to the scenario. Handler or Runnable are more suitable to duplex cases, like chat apps.
It may be my personal preference - but I would use
AsyncTask
in your case. It provides all necessary controls for starting up the task, updating progress as necessary, etc. I have a very similar requirement in my app (send request to server, get response in XML, parse response, do something with the data) - I'm using AsyncTasks for this purpose.Here's how I see it.
Handler
is more for queuing many actions, and gives a bit more control. It's better for repetitive tasks which are generally not restricted to the UI.AsyncTask
provides a simple way to do background processing, not caring much about the lower-level stuff. It's great for relatively small, individual UI updates.IMO, you should use
AsyncTask
. That being said, it's kind of a toss-up.As far I know AsyncTask is the recommended way. I think is the easiest way to implement and the more "Android best practice" for asynchronous tasks.
Could you refer to this question
I'd recommend you to use AsyncTask because it is simplier than other approaches and it suits your needs.
I think you mess a bit these three different entities:
AsyncTask runs a set of actions in a separate thread, can show progress during its work and show notification when the task is completed.
Runnable is a command that can be performed. You should run in a separate thread. Also you should develop a logic in this case how to update progress and how to notify when the task is finished.
Handler is a special class that can handle messages that are sent to the handler's thread.