【发布时间】:2015-05-21 20:46:05
【问题描述】:
我必须多次调用 Web 服务,但每一步都使用上一步中的值,所以现在我有一个巨大的 AsyncTask 链:每个 AsyncTask 都在 AsyncTask 的 onPostExecute() 中执行前一步。这非常非常难看,而且很难修改。我怎样才能避免这种情况?我想把每个步骤放在一个单独的函数中:
int step5() //this function is on the main UI thread
{
return getStep5ValuesFromWebService() + valuesFromPreviousSteps;
}
int getStep5ValuesFromWebService()
{
//do work on new thread
//GetValueFromService(); <-- this is the function that returns an int from the web service, but it has to be called from another thread
}
如何调用GetValueFromService()使step5()函数返回GetValueFromService()函数中计算的值?
【问题讨论】:
-
为什么需要多次调用async task?只需在一个异步任务中完成所有 5 个步骤。如果您需要将其拆分为函数,请在您正在扩展的 asynctask 中执行此操作。你真的需要在 int step5() 中返回值吗?或者你可以在 onPostExcecute() 中设置值吗?
-
+1wldchld。正是我要说的
-
我无法在一个异步任务中完成所有 5 个步骤:每个步骤的调用参数都是在上一步计算的。我需要完成第 1 步才能调用第 2 步。
-
你可以尝试使用监听机制。 OnPostExecute 调用 listener.thisJobIsDone(myParams);无论谁是所有者,都可以调用新的异步任务。