0

我想等到我AsynTask完成后再继续。但是,状态始终显示为RUNNINGAsyncTask已经完成的信号如何返回?为什么我的while循环没完没了?我认为一旦onPostExecute()在任务上被调用,状态就会变为 FINISHED。

private void methodOne(Context context) {

MyNewTask getMyTask = null;

    try {


        getMyTask = new MyNewTask(context, null, null, param1);

        getMyTask.execute(getUrl());

        while(getResourceTask.getStatus().equals(AsyncTask.Status.RUNNING)){

            Log.i("log", "STATUS : " + getMyTask.getStatus());
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
4

1 回答 1

2

Is this method executed in UI thread? If so, onPostExecute() won't have a chance to be executed (UI thread blocked).

You normally don't wait for AsyncTask to complete by looping. This is a serious code smell. You should just start whatever you want to do in onPostExecute().

So, instead of

task.execute();
while(task.getStatus().equals(AsyncTask.Status.RUNNING)) {};
doSomeWork();

You should use:

task.execute();

And:

void onPostExecute(Param... params) {
    doSomeWork();
}

Where doSomeWork() is a method in class that calls AsyncTask. This way you get informed that task has finished.

于 2012-10-08T06:48:13.457 回答