2013-10-08 150 views
0

我也讀過類似的問題,但沒有任何適用於我的作品。 問題是方法getProgress()返回非常大的值(如16300)。我做錯了什麼?顯示下載進度

看到我的代碼

public void download() 
{ 
    RandomAccessFile file = null; 
    InputStream inputStream = null; 
    HttpURLConnection connection = null; 
    try 
    { 
     connection = (HttpURLConnection)url.openConnection(); 
     connection.setRequestMethod("GET"); 
     connection.setDoOutput(true); 
     connection.connect(); 
     String connectLength = connection.getHeaderField("Content-Length"); 

     if(connectLength == null || Integer.parseInt(connectLength) < 1 || connectLength.equals("")) 
      error(); 

     size = Long.parseLong(connectLength); 
     file = new RandomAccessFile(filePath,"rw"); 
     inputStream = new BufferedInputStream(url.openStream()); 
     int read ; 

     while((read = inputStream.read(buffer)) > 0 && status == States.DOWNLOADING) 
     { 
      file.write(buffer,0,read); 
      downloadedS += read; 
     } 
    } 
} 
public float getProgress() 
    { 
     return ((float)downloadedS/size)*100; 
    } 
+0

確實「Content-Length」的響應大小是否正確? –

+0

什麼是'downloadS'的類型?你在哪裏啓動和/或重置它? – blgt

+0

已下載S很長; init在構造函數中。 (public Download(){downloadedS = 0; size = 0;} – dooplaye

回答

1

的AsyncTask能夠正確且容易使用的UI線程。該類允許執行後臺操作並在UI線程上發佈結果,而無需操縱線程和/或處理程序。 AsyncTask