我从一个 URL 获取信息并将该信息发送到多个 URL。我在 AsyncTask
中的“for”上运行它,在第一个 AsyncTask
的 onPostExecute 处,我更改了一个 TextView
并告诉“All已完成”给用户。
但问题是即使 AsyncTask
的子级仍在继续执行,父级 AsyncTask
执行其 onPostExecute
。所以我需要等待他们,我被困住了。
所以,我有两个 AsyncTask 类。这是我发送到网站的类(class):
class SendTo extends AsyncTask <Object,Object,String>{
@Override
protected String doInBackground(Object... strings) {
....
}
protected void onPostExecute(String s) {
super.onPostExecute(s);
//update ui for gathered information
}
}
这是我从网站上得到的任务:
class GetFrom extends AsyncTask <Object,Object,String>{
@Override
protected String doInBackground(Object... strings) {
....
String param = anotherMagicalFunctionThatGivesParamToSend(strings[1]);
for(i = 1; i < websites.length; i++){
publishProgress(websites[i],param);
}
return "";
}
protected void onProgressUpdate(final Object... values) {
super.onProgressUpdate(values);
new SendTo().executeOnExecutor(THREAD_POOL_EXECUTOR, values[1], values[0]);
}
protected void onPostExecute(String s) {
super.onPostExecute(s);
//finish things
}
}
最佳答案
我建议在这种情况下使用回调。
创建接口(interface):
public interface MyCallback {
public void readycallback(int index_thread);
}
头等舱:
class SendTo extends AsyncTask <Object,Object,String>{
private MyCallback cb;
private int i;
public SendTo(int i, MyCallback cb) {
this.cb = cb;
this.i = i;
}
@Override
protected String doInBackground(Object... strings) {
....
}
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (cb != null)
cb.readycallback(i);
//update ui for gathered information
}
}
第二类:
class GetFrom extends AsyncTask <Object,Object,String>{
private boolean[] array_of_completed_tasks = new boolean[websites.length - 1];
@Override
protected String doInBackground(Object... strings) {
....
String param = anotherMagicalFunctionThatGivesParamToSend(strings[1]);
for(i = 1; i < websites.length; i++){
publishProgress(websites[i],param);
}
while(!checkIfAllThreadAreCompleted()) {
//waiting all threads
//you can wait
try {
Thread.sleep(10L);// ten milliseconds
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "";
}
protected void onProgressUpdate(final Object... values) {
super.onProgressUpdate(values);
new SendTo(i, new MyCallback() {
@Override
public void readycallback(int index_thread) {
//this is your ready callback
array_of_completed_tasks[index_thread] = true;
}
}).executeOnExecutor(THREAD_POOL_EXECUTOR, values[1], values[0]);
}
}
private boolean checkIfAllThreadAreCompleted() {
boolean ok = true;
for(i = 0; i < array_of_completed_tasks.length; i++){
ok = ok && array_of_completed_tasks[i];
}
return ok;
protected void onPostExecute(String s) {
super.onPostExecute(s);
//finish things
}
}
或者使用 Threads 以获得更好的编码风格。但我真的认为使用 AsyncTask
是非常丑陋的方法是真正的项目。
关于java - 在处理 onPostExecute 之前等待其他 AsyncTasks 在 AsyncTask 中完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39289601/