如何避免多次使用AsyncTask链接调用?

5

我需要调用多个Web服务,但每个步骤都使用了前一步骤的值,所以现在我有一个巨大的AsyncTasks链:每个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()函数中计算的值?

4
为什么需要多次调用异步任务?只需在一个异步任务中完成所有5个步骤。如果需要将其拆分为函数,请在您正在扩展的异步任务内部执行。你真的需要在int step5()中返回值吗?还是可以在onPostExecute()中设置值? - wldchld
+1wldchld。正是我想说的。 - Kuffs
1
我无法在一个异步任务中完成所有5个步骤:每个步骤的调用参数是在前一个步骤中计算的。我需要先完成步骤1才能调用步骤2。 - kovacs lorand
你可以尝试使用监听器机制。在OnPostExecute中调用listener.thisJobIsDone(myParams);,然后无论是谁拥有它,都可以调用新的asynctask。 - Heisenberg
1个回答

0

你能不能不要做:

private class MyAsync extends AsyncTask<String, Integer, Long> {

    protected Long doInBackground(String... symbols) {
        step1();
        step2();
        step3();
        step4();
        step5();
    }

    private void step1(){}
    private void step2(){}
    private void step3(){}
    private void step4(){}
    private void step5(){}

    protected void onProgressUpdate(Integer... progress) {
    }

    protected void onPostExecute(Long result) {
    }
}

你能否也加上一个解释? - Robert
尽管问题不太具体,但我也不知道如何构建步骤。他声称正在嵌套AsyncTasks,我建议为每个步骤创建方法,并按顺序调用它们,以响应此评论:我无法在一个异步任务中完成所有5个步骤:每个步骤的调用参数都是在前一步中计算出来的。我需要先完成步骤1才能调用步骤2。 - rvogel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接