问题
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