我正在開發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實例發佈到活動或視圖。 –