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.