2011-03-02 32 views
0

我正在開發我的第一個Androïd應用程序,當我想要顯示ProgressDialog以指示進程正在運行時,我遇到問題。 在我的應用程序中,用戶通過按下按鈕來觸發耗時的任務。當用戶按下按鈕時,我的「OnClickListener」的「OnClick」功能被調用。在此功能中,這裏是目前我在做什麼:主題和ProgressDialog

 - creation and configuration of an instance of the ProgressDialog class, 
     - creation of a thread dedicated to the time consuming task, 
     - attempt to display the ProgressDialog using the "show" method, 
     - start of the thread, 
     - main Activity suspended (call of the "wait" function) 
     - wake up of the main Activity by the thread when it is finished 
     - removal of the ProgressDialog by calling the "dismiss" function. 

,一切工作正常(長期任務的結果是正確的),但仍然出現ProgressDialog訥韋爾。我究竟做錯了什麼?

在此先感謝您花費時間來幫助我。

回答

2

您不應該在主要Activity/UI線程中調用wait(),因爲這實際上會凍結UI,包括ProgressDialog,所以它沒有時間淡入並且永遠不會顯示。

嘗試使用正確的多線程:http://developer.android.com/resources/articles/painless-threading.html

final Handler transThreadHandler = new Handler(); 

public void onClick(View v) { 
    // show ProgressDialog... 
    new Thread(){ 
     public void run(){ 
      // your second thread 
      doLargeStuffHere(); 
      transThreadHandler.post(new Runnable(){public void run(){ 
       // back in UI thread 
       // close ProgressDialog... 
      }}); 
     } 
    }.start(); 
} 
0

我會建議使用AsyncTask,因爲它的目的就是精確地處理這類問題。有關如何使用它的說明,請參閱here。請注意,Floern的答案中的鏈接頁面也建議使用AsyncTask

你需要做到以下幾點:

  • AsyncTask
  • 覆蓋它onPreExecute()方法來創建和顯示ProgressDialog。 (你可以在你的子類的成員中持有對它的引用)
  • 重寫它的doInBackground()方法來執行耗時的操作。
  • 覆蓋它的隱藏對話框的方法。
  • 在你的活動中,創建你的子類的一個實例,並在其上調用​​。

如果你讓你的子類成爲你活動的內部類,你甚至可以使用你所有活動的成員。

+0

使用此方法是否滿足原始發佈者的要求,即暫停主要活動,直到耗時操作完成? – shyamal 2012-06-26 18:34:06

+0

他爲什麼要這麼做? UI線程負責在後臺線程運行時顯示(動畫)進度指示器。 (調用wait()會掛起UI線程,而不是Activity)。如果我正確理解了這個問題,那麼該框不包含他的需求,但是他的解決方案會改爲嘗試。 – user634618 2012-09-06 13:20:54