调用Asynctask创建延迟

时间:2012-06-20 13:04:23

标签: android android-asynctask

在我的应用程序中,点击登录页面中的登录后,我必须调用3个API。我有3个AsyncTask来执行此要求。我正在做的是在第一个任务onPostExcecute()中调用第二个任务,在第二个任务的onPostExecute()中调用第三个任务。

TaskA看起来像:

private class TaskA extends AsyncTask<Void, Void, ListA> {

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected ListA doInBackground(Void... params) {
        ListA listA;//its an arraylist          

        listA = //calling my API

        if(listA != null) {
            //writing listA as serialized into sdcard.
        }

        return listA;
    }

    @Override
    protected void onPostExecute(ListA listA) {
        for(ListAValues value : listA) {
            new TaskB().execute(value);             
        }
    }
}

TaskB:

private class TaskB extends AsyncTask<ListA, Void, ListB> {

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected ListB doInBackground(ListA... params) {
        ListB listB;//its an arraylist          

        listB = //calling my API

        if(listB != null) {
            //writing listB as serialized into sdcard.
        }

        return listB;
    }

    @Override
    protected void onPostExecute(ListB listB) {
        new TaskC().execute(listB);
    }
}

TaskC:

private class TaskC extends AsyncTask<ListB, Void, ListC> {

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected ListC doInBackground(ListB... params) {
        ListC listC;//its an arraylist          

        listC = //calling my API

        if(listC != null) {
            //writing listC as serialized into sdcard.
        }

        return listC;
    }

    @Override
    protected void onPostExecute(ListC listC) {
        //moving to my landing page.
    }
}

问题出在着陆页上,屏幕闪烁着黑白色。(白色是我的着陆页活动的背景色)。我实施的方式是对的吗?或者我是否需要更改代码?请帮帮我。

2 个答案:

答案 0 :(得分:2)

您不需要使用3个单独的AsyncTask。您可以使用单个AsyncTask,如下所示:

private class TaskA extends AsyncTask<Void, Void, Void> {

    @Override
    protected void doInBackground(Void... params) {
        ListA listA;//its an arraylist          

        listA = //calling my API

        if(listA != null) {
            //writing listA as serialized into sdcard.
        }

        for(ListAValues value : listA) {
            ListB listB;//its an arraylist          

            listB = //calling my API

            if(listB != null) {
                //writing listB as serialized into sdcard.
            }
            ListC listC;//its an arraylist          

            listC = //calling my API

            if(listC != null) {
                //writing listC as serialized into sdcard.
            }


        }
        return null;
    }

}

答案 1 :(得分:0)

Rajesh,你的代码无法帮助我。

我的应用是API级别11.所以我使用了

Task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR)

这帮助了我,我的代码工作正常。