您可以通过对返回的AsyncTask调用AsyhncTask的get()方法来获得结果,但是当它等待获取结果时,它将把它从异步任务变成同步任务。
String serverResponse = apiObj.execute(namevaluePairs).get();
由于您的AsyncTask位于单独的类中,因此您可以创建一个接口类并在AsyncTask中对其进行声明,并以您希望从中访问结果的类中的委托形式实现新的接口类。此处提供了一个很好的指南:由于AsyncTask是一个单独的类,如何将OnPostExecute()的结果获取到主要活动中?。
我将尝试将以上链接应用于您的上下文。
(IApiAccessResponse)
public interface IApiAccessResponse { void postResult(String asyncresult);}(ApiAccess)
public class ApiAccess extends AsyncTask<List<NamevaluePair>, Integer, String> {... public IApiAccessResponse delegate=null; protected String doInBackground(List<NamevaluePair>... namevaluePairs) { //do all your background manipulation and return a String response return response } @Override protected void onPostExecute(String result) { if(delegate!=null) { delegate.postResult(result); } else { Log.e("ApiAccess", "You have not assigned IApiAccessResponse delegate"); } } }(您的主类,实现IApiAccessResponse)
ApiAccess apiObj = new ApiAccess (0, "/User");//Assign the AsyncTask's delegate to your class's context (this links your asynctask and this class together)apiObj.delegate = this;apiObj.execute(namevaluePairs); //ERROR//this method has to be implement so that the results can be called to this classvoid postResult(String asyncresult){ //This method will get call as soon as your AsyncTask is complete. asyncresult will be your result.}


