我想从异步任务中获取结果。如果我使用task.execute.get,我的UI将被冻结。我希望我的异步任务是独立的类,所以我不想将结果处理代码放在 onPostExecute 中。我在这里找到了一些有关异步任务回调数据的信息:http://blog.evoxmusic.fr/content/how-implement-callback-asynctask http://blog.evoxmusic.fr/content/how-implement-callback-asynctask
和这里:android asynctask发送回调到ui https://stackoverflow.com/questions/9963691/android-asynctask-sending-callbacks-to-ui
但问题是:
1-我不知道什么时候处理结果?
2-为什么要使用接口?
3-使用接口与简单地将结果放入异步任务中 onPostExecute 的公共字段有什么区别?
这是我的异步类:
public class AsyncCallWs extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
public String methodName="";
private WebService ws;
private ArrayList<ServiceParam> paramsList;
private boolean hasParams;
public AsyncCallWs(Activity activity,String methodName) {
xLog.position();
try {
this.dialog = new ProgressDialog(activity);
this.methodName = methodName;
hasParams = false;
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
public AsyncCallWs(Activity activity,String methodName,ArrayList<ServiceParam> params) {
xLog.position();
try {
this.dialog = new ProgressDialog(activity);
this.methodName = methodName;
this.paramsList = params;
hasParams = true;
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
@Override
protected void onPreExecute() {
this.dialog.setMessage(PersianReshape.reshape("Loading..."));
this.dialog.show();
}
@Override
protected String doInBackground(String... params) {
xLog.position();
String result = "No async task result!";
try {
ws = new WebService(PublicVariable.NAMESPACE, PublicVariable.URL);
if (!hasParams){
result = ws.CallMethod(methodName);
}
else{
xLog.info("THIS METHOD IS: "+ methodName);
result = ws.CallMethod(methodName,paramsList);
xLog.info("THIS RESULT IS: "+ result);
}
} catch (Exception e) {
xLog.error(e.getMessage());
}
return result;
}
@Override
protected void onPostExecute(String result) {
xLog.position();
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
xLog.info("Output of current AsyncTask is:"+ result);
}
}
1-我不知道什么时候处理结果?
结果将被处理在onPostExecute
,这反过来会在实现该接口的任何类中调用您的接口方法。所以实际的 UI 事情都会发生在你的Activity
or Fragment
或者任何实现接口回调的东西。您可以将任何您想要的数据传递给它。
2-为什么要使用接口?
接口是将逻辑与您的逻辑分离的好方法AsyncTask
以及任何课程(我假设Activity
or Fragment
)正在实施它。这也意味着任何实现此接口的类都可以处理此接口的结果AsyncTask
,它变得很容易重复使用。
3-使用接口与简单地将结果放入异步任务中 onPostExecute 的公共字段有什么区别?
您仍然不会收到回电 - 您将如何Activity
or Fragment
知道该字段何时被填充并准备好被询问吗?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)