How to get AsyncTask Completed Status From Non Activity Class

自作多情 提交于 2020-01-25 07:18:49

问题


I want to wait until my AsynTask is finished before continuing on. The status always shows as RUNNING however. How can the AsyncTask signal back that is has finished? Why is my while loop endless? I thought that once onPostExecute() is called on the task the status gets changed to 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();
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/12776293/how-to-get-asynctask-completed-status-from-non-activity-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!