Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connecting to a webservice from android - AsyncTask or Service?

I'm writing an android app that will connect to a REST/JSON webservice. Users will be retrieving information, uploading comments, downloading and uploading images etc.

I know that I shouldn't keep all this network communication in the Activity/UI thread, as it will cause ANRs. What I'm confused about is whether I should use an AsyncTask or a Service with "manual" threading to accomplish this;

With a Service, I'd simply have a public method for each method in the webservice's API. I'd then implement threading within each of these methods.

If I used an AsyncTask, I would create a helper class that defined AsyncTasks for each method in the webservice's API.

Which method is preferred? Interaction with the webservice will only happen while the user is in the Activity. Once they switch to another application, or exit the program, there is no need for communication with the webservice.

like image 721
football Avatar asked Mar 07 '11 08:03

football


People also ask

What is the use of AsyncTask in Android?

This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field. onPostExecute(Result) , invoked on the UI thread after the background computation finishes.

How can I use AsyncTask in different activities in android?

AsyncTask class is firstly executed using execute() method. In the first step AsyncTask is called onPreExecute() then onPreExecute() calls doInBackground() for background processes and then doInBackground() calls onPostExecute() method to update the UI.

Which method is used to start the background thread of AsyncTask?

The following code snippet must be present in the MainActivity class in order to launch an AsyncTask. MyTask myTask = new MyTask(); myTask. execute(); The execute method is used to start the background thread in the excerpt above, where we've used a sample class name that extends AsyncTask.


1 Answers

I recommend you go for the AsyncTask solution. It is an easy and straightforward way of running requests or any other background tasks of the UI-thread.

It's also easy to implement e.g. onProgressUpdate if you need to show a progress bar of some sort while running your requests.

like image 187
Eric Nordvik Avatar answered Oct 02 '22 20:10

Eric Nordvik