问题描述
我想等到我的 AsynTask
继续之前完成。
状态总是显示为运行但是。
如何能在的AsyncTask
信号回那就是已经完成?
为什么我的while循环没完没了?我认为,一旦 onPostExecute()
上调用任务
状态得到改变到成品。
私人无效methodOne(上下文的背景下){MyNewTask getMyTask = NULL; 尝试{
getMyTask =新MyNewTask(背景下,NULL,NULL,参数1); getMyTask.execute(的getURL()); 而(getResourceTask.getStatus()。等于(AsyncTask.Status.RUNNING)){ Log.i(日志,状态:+ getMyTask.getStatus());
} }赶上(例外五){
e.printStackTrace();
}
}
时,这种方法在UI线程中执行?如果是这样, onPostExecute()
不会被执行(UI线程阻塞)的机会。
您通常不等待的AsyncTask通过循环完成。这是一个严重code气味。
你应该刚开始无论你想在做 onPostExecute()
。
因此,代替
task.execute();
而(task.getStatus()等于(AsyncTask.Status.RUNNING)){};
做一些工作();
您应该使用:
task.execute();
和
无效onPostExecute(参数... PARAMS){
做一些工作();
}
其中, doSomeWork()
是类中的方法调用的AsyncTask
。这样,您就得到通知,任务已经完成了。
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 taskthe 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();
}
}
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.
这篇关于如何获得的AsyncTask完成的状态从非活动课的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!