我有一个活动类,它两次调用后台AsyncTask
BackgroundTask bt1 = new BackgroundTask(this, ApiHelper.GET);
bt.execute(url1);
BackgroundTask bt2 = new BackgroundTask(this, ApiHelper.POST, params);
bt.execute(url2);
一个用于获取数据,另一个用于将数据发布到服务器。
此AsyncTask的构造函数如下
public BackgroundTask(Context context, String method) {
this.context = context;
this.method = method;
this.callback = (onBackgroundTaskListener<String>) context;
}
public BackgroundTask(Context context, String method, ArrayList<NameValuePair> params) {
this.context = context;
this.method = method;
this.callback = (onBackgroundTaskListener<String>) context;
this.params = params;
}
现在MainActivity.class通过onBackgroundTaskListener<String>
接口实现为
public interface onBackgroundTaskListener<T> {
void onTaskComplete(T result);
}
AsyncTask类的String result
的onPostExecute返回或传递回调用类,如下所示。
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
callback.onTaskComplete(result);
}
现在,我在MainActivity中有一种方法(onTaskComplete)处理来自一个后台任务的两个响应。我想使用该条件来找出返回的执行结果,例如...
@Override
public void onTaskComplete(String result) {
if (execution == 1) {
// Parse the GET result
} else if(execution == 2) {
// Parse the POST result
}
}
我不想实现多个AsyncTask,而是想使用单个AsyncTask来实现它,并希望在单个活动中多次调用此AsyncTask。实现该目标的可能方式应该是什么。
答案 0 :(得分:0)
enum BackgroundType{ GET, POST }
public interface onBackgroundTaskListener<T> {
void onTaskComplete(T result, BackgroundType type);
}
--------------------------
BackgroundTask bt1 = new BackgroundTask(this, ApiHelper.GET, GET);
bt.execute(url1);
BackgroundTask bt2 = new BackgroundTask(this, ApiHelper.POST, params, POST);
bt.execute(url2);
------------------------
@Override
public void onTaskComplete(String result, BackgroundType type) {
switch(type){
case GET:
break;
case POST:
break;
}
}
答案 1 :(得分:0)
我建议您创建一个新类,并在创建String
并从AsyncTask
返回结果时使用该类而不是AsyncTask
然后,新类可以封装所需的字符串以及所需的其他变量。
例如:
// Create a new class to hold the result of `AsyncTask` execution
public class TaskExecutionResult {
public String method;
public String resultString;
}
// When subclassing AsyncType assign TaskExecutionResult as return type
// Please replace URL with input parameters you require (perhaps a method string)
private class BackgroundTask extends AsyncTask<URL, Integer, TaskExecutionResult> {
// doInBackground will now return TaskExecutionResult type of object
protected TaskExecutionResult doInBackground(URL... urls) {
// Here populate a value which will identify your AsyncTask into return value (perhaps a method string)
...
}
// onPostExecute will also accept TaskExecutionResult type of object
protected void onPostExecute(TaskExecutionResult result) {
super.onPostExecute(result);
callback.onTaskComplete(result);
}
}
然后在onTaskComplete中使用TaskExecutionResult:
public void onTaskComplete(TaskExecutionResult result) {
if (result.method.equals("GET")) {
// Parse the GET result (from result.resultString)
} else if(result.method.equals("POST")) {
// Parse the POST result (from result.resultString)
}
}
如果需要添加更多返回变量,这种方法还可以使您轻松更新结果对象。