2010-10-25 165 views
0

優雅的解決方案優雅的解決方案?

嘿人。 我目前工作的一個項目,我想爲實現一個優雅的解決方案,我累了簡易的解決方案。

讓我試着解釋我的「問題」給你:

我的應用程序,這部分的任務很簡單:

我想我的應用程序下載一些東西,過程中下載的文件背景,同時顯示ProgressDialog。之後,內容應該返回到ListActivity中顯示的字符串列表中。到目前爲止,沒什麼大不了的:

下載和處理的東西是一個子類的AsyncTask,並要求從主活動不同的類。但現在我的問題:

凡撥打Progressdialog? GUI線程如何與ProgressDialog「反應」?我應該從處理類中調用ProgressDialog還是更好地阻止主類,等待通知?

問候

EnflamedSoul

+1

你看着一個叫做'觀察者Pattern'模式? – 2010-10-25 15:50:50

回答

0

定義你的陸侃對話框,全局變量。

ProgressDialog pd; 

如果你要關火的AsyncTask:

showYourProgressDialog; 
thread = new aThread().execute(); 

在你的類:

public class aThread extends AsyncTask<Void, Void, Void> { 
     @Override 
     protected Void doInBackground(Void... args) { 
      try { 
       //Do your downloading and stuff 
           asyncHandler.sendMessage(asyncHandler.obtainMessage(0)); 
      } catch (Exception e) { 
       Log.e("1", "Error", e); 
      } 
      return null; 
     } 
    } 

Handler asyncHandler = new Handler() { 
     public void handleMessage(Message msg) { 
      pd.dismiss(); 
      if (msg.what == 0) { 
       //update what you need to    
      }   
     } 
    }; 
+0

MH好的,謝謝,這給了我該怎麼做一個好主意! – EnflamedSoul 2010-10-25 15:59:28

2

blindstuffs anwser會在正確的方向,但我不會用處理更新進度的處理程序。的AsyncTask有自己的函數來處理這個問題,這是恕我直言,更容易使用和更適合進入的AsyncTask類

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { 
    protected Long doInBackground(URL... urls) { 
    int count = urls.length; 
    long totalSize = 0; 
    for (int i = 0; i < count; i++) { 
     totalSize += Downloader.downloadFile(urls[i]); 
     publishProgress((int) ((i/(float) count) * 100)); 
    } 
    return totalSize; 
    } 

    protected void onProgressUpdate(Integer... progress) { 
     setProgressPercent(progress[0]); 
    } 

    protected void onPostExecute(Long result) { 
     showDialog("Downloaded " + result + " bytes"); 
    } 
} 

這個例子是從official Android SDK documentation拍攝。使用publishProgress的好處是,你可以通過一個以上的價值,取決於傳入doInBackground(即,如果您正在下載超過1個文件)參數的個數。

+0

謝謝,這真的幫了我。我搞砸了一些東西,但我想現在我有一個很好的解決方案。謝謝! – EnflamedSoul 2010-10-26 05:01:56