我正在关注 codelearn 的教程,并尝试创建一个 AsyncTask,它生成推文并执行另一个 AsyncTask 以写入缓存文件。
我有 Thread.sleep,因此首次加载时的 UI 会等待推文写入缓存文件。首先我执行 AysncTask new AsyncWriteTweets(this.parent).execute(tweets);
然后 hibernate 10 秒。
但在 logcat 中,我可以看到 AsyncWriteTweets 也会在 10 秒 sleep 后执行。因此 onPostExecute 在将推文写入缓存文件之前执行,给出一个空白屏幕。
public class AsyncFetchTweets extends AsyncTask<Void, Void, Void> {
private TweetListActivity parent;
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
ArrayList[] temp;
public AsyncFetchTweets(TweetListActivity parent){
this.parent = parent;
}
@Override
protected Void doInBackground(Void... params) {
int result = 0;
Log.d("ASync", "Calling asycn");
for (int i=0;i<4;i++){
Tweet tweet = new Tweet();
tweet.setTitle("Title Async Very New" + i);
tweet.setBody("Body text for tweet no " + i);
tweets.add(tweet);
}
new AsyncWriteTweets(this.parent).execute(tweets);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result){
Log.d("Async", "on Post execute");
this.parent.renderTweets();
}
}
PS: My assumption is AsyncTask should create a new thread, hence Thread.sleep in parent should not stop child. If it is otherwise please advise how can I overcome this issue.
最佳答案
这个:
new AsyncWriteTweets(this.parent).execute(tweets);
是错误的,AsyncTask 必须在 UI 线程而不是 Worker 线程上执行。您可以使用 Handler 和 post runnable 来安全地执行它。
引用线程规则:
execute(Params...) must be invoked on the UI thread.
http://developer.android.com/reference/android/os/AsyncTask.html
上述链接的另一部分是Order of execution
, :
Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
因此您的第一个异步任务必须在下一个异步任务开始之前结束,但是您可以通过使用带有 THREAD_POOL_EXECUTOR 的 executeOnExecutor(java.util.concurrent.Executor, Object[]) 来恢复之前的并行行为。
execute
必须在 UI 线程上完成。
关于java - Thread.sleep 停止所有嵌套的异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31168566/