I’m developing an application in Android. The application can post a HTTP request to specific web server. That post request must run asyncronously, so I create a thread to do the job. But I need a callback that will be called at thread end and it must be called from thread that call the `post` method.
My post method looks like this:
interface EndCallback
{
public void Success(String response);
public void Fail(Exception e);
}
public void post(final String url, final List<NameValuePair> data, EndCallback callback)
{
Thread t = Thread.currentThread();
(new Thread()
{
public void run()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try
{
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse r = httpclient.execute(httppost);
HttpEntity en = r.getEntity();
String response = EntityUtils.toString(en);
//I want to call callback.Success(response)
//here from thread t
}
catch (Exception ex)
{
//And I want to call callback.Fail(ex)
//here from thread t
}
}
}).start();
}
Creating new threads an Android is highly discouraged for most applications. This seems like the perfect place for an AsyncTask. It has built-in methods that switch between threads, without needing to manually manage thread creation.
One approach I’ve used in a similar situation is to combine the task with an
enumof possible success states:The
doInBackgroundmethod will be run in a separate thread, managed by the OS. When that thread finishes,onPostExecutewill be run on the thread that started the task, which is typically the UI thread.If you need to set up callback objects, just add a constructor to the HttpPostTask and do any initialization you need. Your client code will then just need to create and execute the task:
You can also pass parameters into
execute()as well, which accepts a variable number of arguments of the first generic type in the class signature. Theparamsvariable in thedoInBackgroundis an array of things that were passed into execute, all of the same type.Passing params into
executeis useful if, for example, you wanted to post to multiple URLs. For most dependencies, setting them in the constructor is simplest approach.