一个异步任务用于多个活动



我正在编写一个使用WebServices检索数据的应用程序。最初,对于每个需要WebService数据的活动,我都有一个私有的AsyncTask类。但是我决定通过将AsyncTask创建为公共类来简化代码。一切都很好,但我的问题是当我想访问从AsyncTask检索到的数据时。

例如,这是我的AsyncTask类。

public class RestServiceTask extends AsyncTask<RestRequest, Integer, Integer> {
/** progress dialog to show user that the backup is processing. */
private ProgressDialog dialog;
private RestResponse response;
private Context context;
public RestServiceTask(Context context) {
this.context = context;
//...Show Dialog
}
protected Integer doInBackground(RestRequest... requests) {
int status = RestServiceCaller.RET_SUCCESS;
try {
response = new RestServiceCaller().execute(requests[0]);
} catch(Exception e) {
//TODO comprobar tipo error
status = RestServiceCaller.RET_ERR_WEBSERVICE;
e.printStackTrace();
}
return status;
}
protected void onPreExecute() {
response = null;
}
protected void onPostExecute(Integer result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
switch (result) {
case RestServiceCaller.RET_ERR_NETWORK:
Toast.makeText(
context,
context.getResources().getString(
R.string.msg_error_network_unavailable),
Toast.LENGTH_LONG).show();
break;
case RestServiceCaller.RET_ERR_WEBSERVICE:
Toast.makeText(
context,
context.getResources().getString(
R.string.msg_error_webservice), Toast.LENGTH_LONG)
.show();
break;
default:
break;
}
}
public RestResponse getResponse() throws InterruptedException {
return response;
}
}

RestServiceCallerRestRequestRestResponse是我创建的类。我使用的任务是这样的:

RestRequest request = new JSONRestRequest();
request.setMethod(RestRequest.GET_METHOD);
request.setURL(Global.WS_USER);
HashMap<String, Object> content = new HashMap<String, Object>() {
{
put(Global.KEY_USERNAME, username.getText().toString());
}
};
request.setContent(content);
RestServiceTask task = new RestServiceTask(context);
task.execute(request);

这段代码运行良好,并且正确地调用了web服务,我的问题是当我想要访问响应时。在AsyncTask中,我创建了方法getResponse,但当我使用它时,它会返回一个null对象,因为AsyncTask仍在进行中,所以此代码不起作用:

//....
task.execute(request);
RestResponse r = new RestResponse();
r = task.getResponse();

CCD_ 11将是空指针,因为CCD_。

我尝试在getResponse函数中使用此代码,但它不起作用:

public RestResponse getResponse() throws InterruptedException {
while (getStatus() != AsyncTask.Status.FINISHED);
return response;
}

我原以为使用while循环,线程会等到AsyncTask完成,但我实现的是一个无限循环。

所以我的问题是,我怎么能等到AsyncTask完成,这样getResponse方法就会返回正确的结果?

最好的解决方案是使用onPostExecute方法,但由于AsyncTask被许多活动使用,我不知道该怎么办

尝试创建一个回调接口。这个异步任务问题的答案是Android中异步任务的公共类?对此给出了很好的解释