2011-09-06 127 views
0

我有以下代碼:的Android的AsyncTask - onPostExecute不叫(ProgressDialog)

try { 
    res = new Utils(ubc_context).new DownloadCalendarTask().execute().get(); 
} catch (InterruptedException e) { 
    Log.v("downloadcalendar", "interruptedexecution : " + e.getLocalizedMessage()); 
    res = false; 
} catch (ExecutionException e) { 
    Log.v("downloadcalendar", "executionexception : " + e.getLocalizedMessage()); 
    res = false; 
} 

Log.v("displaymenu", "A"); 

public class Utils { 

private Context context; 

public Utils(Context context) { 
    this.context = context; 
} 

public class DownloadCalendarTask extends AsyncTask<Void, Void, Boolean> { 

    private ProgressDialog dialog; 

    public DownloadCalendarTask() { 

    dialog = new ProgressDialog(context); 

    } 

    protected void onPreExecute() { 
     Log.v("preexecute", "A"); 
     dialog.setMessage("Loading calendar, please wait..."); 
     Log.v("preexecute", "B"); 
     dialog.show(); 
     Log.v("preexecute", "C"); 

    } 

    protected Boolean doInBackground(Void... arg0) { 
     // do some work here... 
     return (Boolean) false; 
    } 

    protected void onPostExecute() { 
     Log.d("utils", "entered onpostexecute"); 
     dialog.dismiss(); 
    } 

} 
} 

代碼的第一部分被附着到onClick偵聽的按鈕。當我點擊按鈕,該按鈕閃爍(因爲它顯示它已被點擊),然後約8秒後出現的對話框中加載但從未完成。

根據logcat,只要我點擊按鈕onPreExecute執行,因爲是Dialog.show(),所以我的第一個問題是爲什麼有這8秒的延遲?在這8秒鐘內,logcat顯示doInBackground正在執行。但是,根據logcat(這是第二個問題)onPostExecute永遠不會被調用(所以Dialog.dismiss())永遠不會運行。

Logcat顯示DownloadCalendarTask().execute().get()之後的所有內容都正在執行,所以就好像onPostExecute剛剛被跳過一樣。

非常感謝您的幫助!

回答

1

您正在調用AsyncTask.get(),導致UI線程在AsyncTask執行時被阻塞。

new DownloadCalendarTask().execute().get(); 

如果去掉調用get(),它會異步執行,並得到所需要的結果。

new DownloadCalendarTask().execute(); 

編輯: 您還需要將參數更新到您的onPostExecute方法,他們需要包括的結果。例如

protected void onPostExecute(Boolean result) { 
+0

謝謝,我會嘗試。但是,如果我刪除get()是否還有一個簡單的方法來檢索AysncTask的結果? – Jonny

+0

檢索結果的最簡單方法是使的AsyncTask一個內部類的活動,然後從onPostExecute方法調用您的活動的方法來傳遞活動的結果。 – Rob

+0

我做了這個改變,現在ProgressDialog直接出現了,但是現在doInBackgroundAction中的代碼被執行了,並且它到達了return語句的結尾,但是它似乎什麼都不做,並且progressdialog從不結束。同樣,onPostExecute不會被調用 – Jonny