tags:

views:

1913

answers:

2

I've seen any number of examples and they all seem to solve this problem differently. Basically I just want the simplest way to make the request that won't lock the main thread and is cancelable.

It also doesn't help that we have (at least) 2 HTTP libraries to choose from, java.net.* (such as HttpURLConnection) and org.apache.http.*.

Is there any consensus on what the best practice is?

A: 

You should read this short post from Simon Judge website:

http://www.androidsoftwaredeveloper.com/2009/03/19/how-to-do-asynchronous-http/

QuickRecipesOnSymbianOS
Thanks, I had come across that (and I actually own that book). I guess I was just wondering if this was the "right" way. If you Google around for a while you'll find tons of examples and they all seem to work differently.
fiXedd
+8  A: 

The Android 1.5 SDK introduced a new class, AsyncTask designed to make running tasks on a background thread and communicating a result to the UI thread a little simpler. An example given in the Android Developers Blog gives the basic idea on how to use it:

public void onClick(View v) {
   new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask {
   protected Bitmap doInBackground(String... urls) {
      return loadImageFromNetwork(urls[0]);
   }

   protected void onPostExecute(Bitmap result) {
      mImageView.setImageBitmap(result);
   }
}

The doInBackgroundThread method is called on a separate thread (managed by a thread pooled ExecutorService) and the result is communicated to the onPostExecute method which is run on the UI thread. You can call cancel(boolean mayInterruptIfRunning) on your AsyncTask subclass to cancel a running task.

As for using the java.net or org.apache.http libraries for network access, it's up to you. I've found the java.net libraries to be quiet pleasant to use when simply trying to issue a GET and read the result. The org.apache.http libraries will allow you to do almost anything you want with HTTP, but they can be a little more difficult to use and I found them not to perform as well (on Android) for simple GET requests.

jargonjustin
Thanks. I had actually found the AsyncTask(in 1.5) and UserTask(for 1.1) and have written a generic HttpTask. Pretty much the only thing I have left to do is figure out how to handle a screen rotation while a request is active.
fiXedd