2013-04-23 41 views
0

我有一個應用程序,使一些文件的下載和解壓縮,我每一秒發佈我的進度使用System.currentTimeMillis()來比較已過去的時間。以間隔發佈進度的最佳方法是什麼? (談論性能)

我的問題是,代碼似乎做了太多的工作,每個字節寫入或存檔unziped,獲取當前時間,並與開始時間比較,以顯示或不。我的問題是有沒有更好的方式來使它不失性能?

我的代碼來比較下載經過時間:

protected void afterWrite(int n) throws IOException { 
    super.afterWrite(n); 

    if (DownloadAndUnzipService.canceled) { 
     throw new IOException(); 
    } 

    if (MainViewActivity.isPaused) { 
     throw new IOException(); 
    } 
    bytesWritten += n; 

    showTime = System.currentTimeMillis(); 

    if (showTime - startTime > 1000) { 

     Bundle resultData = new Bundle(); 
     resultData.putLong("bytesWritten", bytesWritten); 
     resultData.putString("typeDownload", typeDownload); 
     resultData.putInt("imageIndex", index); 
     receiver.send(Constants.UPDATE_PROGRESS, resultData); 

     startTime = showTime; 
    } 

} 

我的代碼來比較解壓經過時間:

... 
    if (showTime - startTime > 1000) { 
          Bundle resultData = new Bundle(); 
          resultData.putInt("progress", (int) (filesWritten * 100/fileLength)); 
          resultData.putInt("imageIndex", i); 
          resultData.putString("typeDownload", typeDownload); 
          receiver.send(Constants.UPDATE_ZIP_PROGRESS, resultData); 

          startTime = showTime; 
         } 

         ze = zis.getNextEntry(); 
        } 

回答

1

使用Timer API。定時器允許在指定的時間量之後重複執行特定的一組代碼。可能適合你的情況。

參考Android Documentation

Timer t = new Timer(); 
t.scheduleAtFixedRate(new TimerTask() { 

    @Override 
    public void run() { 
     //Called each time when 1000 milliseconds (1 second) (the period parameter) 
    } 

}, 
//Set how long before to start calling the TimerTask (in milliseconds) 
0, 
//Set the amount of time between each execution (in milliseconds) 
1000); 
相關問題