AsyncTask#onPreExecute,API说明是"Runs on the UI thread before doInBackground.",如果是在子线程中启动了此AsyncTask,log显示onPreExecute是跑在子线程里的(线程id和启动的子线程id一样),大神能给解释下?
new AsyncTask<Void, Void, Void>(){
@Override
protected void onPreExecute() {
android.util.Log.e("tag", "#onPreExecute, " + Thread.currentThread().getId());
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
android.util.Log.e("tag", "#doInBackground, " + Thread.currentThread().getId());
}
@Override
protected void onPostExecute(Void result) {
android.util.Log.e("tag", "#onPostExecute, " + Thread.currentThread().getId());
super.onPostExecute(result);
}
}.execute((Void)null);
------解决思路----------------------
你放在子线程里启动是错误的,AsyncTask是辅助用来后台执行,然后更新UI的,只能在UI线程下启动
Threading rules
There are a few threading rules that must be followed for this class to work properly:
The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
The task instance must be created on the UI thread.
execute(Params...) must be invoked on the UI thread.
http://developer.android.com/intl/zh-cn/reference/android/os/AsyncTask.html
------解决思路----------------------
应该是创建AsyncTask并启动没有在主线程中,只有这样才能对后续的onPostExecute()对UI进行操作。如需了解更多地关于AsyncTask,可以看看这篇文章http://droidyue.com/blog/2014/11/08/bad-smell-of-asynctask-in-android/