我正在开发一个 Android 应用程序。应用程序可以将 HTTP 请求发布到特定的 Web 服务器。该发布请求必须异步运行,因此我创建了一个线程来完成这项工作。但是我需要一个将在线程结束时调用的回调,并且必须从调用`post`方法的线程中调用它。
我的post
方法如下所示:
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();
}