2013-10-08 151 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