看來你可以從別的地方開始的AsyncTask比主線程,但postExecute是在主線程實際執行。 這裏是我的測試,告訴我,如果它似乎是合乎邏輯您:
public class AsyncLoader extends AsyncTask<Context, String, Boolean> {
private ConnectivityManager cm;
private ArrayList<Contact> nameList;
private Context ctx;
private static int i = 0;
@Override
protected Boolean doInBackground(Context... params) {
ctx = params[0];
cm = (ConnectivityManager) params[0].getSystemService(Activity.CONNECTIVITY_SERVICE);
if (i < 3) {
i++;
new AsyncLoader().execute(ctx);
System.out.println("Thread name (from doInBackground) : " + Thread.currentThread().getName());
System.out.println("compteur async " + i);
}
if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable()) {
nameList = (ArrayList<Contact>) ContactLoaderXml.loadContactsData(); //this is a loading from the web + sax parser
return true;
} else {
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
System.out.println("Thread name (from postexecute) : " + Thread.currentThread().getName());
}
}
這裏是任務後的堆棧跟蹤:
I/System.out( 641): Thread name (from doInBackground) : AsyncTask #1
I/System.out( 641): compteur async 1
I/System.out( 641): Thread name (from doInBackground) : AsyncTask #2
I/System.out( 641): compteur async 2
I/System.out( 641): Thread name (from doInBackground) : AsyncTask #3
I/System.out( 641): compteur async 3
I/System.out( 641): Thread name (from postexecute) : main
I/System.out( 641): Thread name (from postexecute) : main
I/System.out( 641): Thread name (from postexecute) : main
I/System.out( 641): Thread name (from postexecute) : main
我不知道爲什麼執行後完成4次雖然...
文檔*對我來說似乎有誤導性,但我沒有跑過你得到的異常是我的經驗,當在UI線程外部使用'AsyncTask'時,onPostExecute'發生在調用線程中,而不一定是UI線程(如果UI需要被操作,則需要'Handler')。 – 2010-07-21 16:07:30