2015-06-02 9 views
0

我已將zip4j庫添加到我的Android項目中。這是非常容易使用。使用while循環來報告進度和完成是否正確?

ZipFile zipFile = new ZipFile(downloadedFilePath); 
zipFile.extractAll(context.getFilesDir().getPath()); 

但是有一個特點是我關心的。相反訂閱獲取解壓的進步,他們用while-loop如下:

while (pm.getState() == ProgressMonitor.STATE_BUSY) { 
    // my progress handler is here 
} 

如果我需要知道,解壓完成後,我應該按如下方式使用它:

while (pm.getState() == ProgressMonitor.STATE_BUSY) { 
    // the loop runs until progress monitor changes its status 
} 
if (pm.getResult() == ProgressMonitor.RESULT_SUCCESS) { 
    // my code to handle completion 
} 

對我來說它看起來像反模式和糟糕的編碼。我應該在我的項目中使用,還是切換到另一個zip庫?

回答

1

while循環將使用CPU資源並保持繁忙。我建議使用Thread並休息一會兒,然後再次檢查pm.getState()並更新您的進度條

1

對於這類任務最好使用AsyncTask

開始顯示onPreExecute上的進度,提取doInBackground中的文件,並取消onPostExecute中的進度。

您也可以使用onProgresUpdate來顯示工作的確切進度。

這也將確保提取工作發生在後臺線程中,並保持UI線程空閒。