我正在开发Android中的应用程序。应用程序可以向特定的Web服务器发布HTTP请求。该发布请求必须异步运行,因此我创建了一个线程来完成这项工作。但是我需要一个将在线程结束时调用的回调函数,并且它必须从调用`post`方法的线程调用。Android:从特定线程执行方法
我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();
}
查看[无痛线程](http://developer.android.com/resources/articles/painless-threading.html)了解许多选项,包括Handler,AsyncTask或将Runnable实例发布到活动或视图。 –