2013-06-19 45 views
0

我試圖從FTP服務器上下載電影。它可以成功下載,但無法看到下載的進度。您能否告訴我爲什麼publishProgress()運行不正常?Android Asyck任務下載無法更新進度對話框

下面是我的代碼

public void doClick(View v){ 
    boolean x = decodedLink.startsWith("ftp://");  
    boolean y = decodedLink.startsWith("http://"); 
    if(x ==true && y==false) 
    { 
     //ftp 

     myurl = null; 
     try { 
      myurl = new URL("ftp://newrising:[email protected]/dummy/giant.mp4"); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } 

     pd = new ProgressDialog(this); 
     pd.setTitle("EOrder"); 
     pd.setMessage("Downloading file. Please wait..."); 
     pd.setIndeterminate(false); 
     pd.setMax(100); 
     pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
     pd.setCancelable(true); 
     new FTPDownload().execute(myurl); 

    }  
    else if(x ==false && y==true) 
    { 
     //http 
    } 
    else 
    { 
     //invalid message 
    } 
} 




class FTPDownload extends AsyncTask<URL , Integer , Void>{ 

    boolean running = true; 
    int count ; 
    Date today = Calendar.getInstance().getTime();  
    Format formatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss"); 
    String reportDate = formatter.format(today); 


    String file = reportDate + "_" + "giant.mp4"; 

    @Override 
    protected Void doInBackground(URL... params) { 
     // TODO Auto-generated method stub 
     Log.d("******", "Background thread starting......"); 
     try 
     { 
      URL url = new URL("ftp://newrising:[email protected]/dummy/giant.mp4"); 
      URLConnection conection = url.openConnection(); 
      conection.connect(); 
      int lenghtOfFile = conection.getContentLength();   
      Log.d("lenghtOfFile","values: "+lenghtOfFile); 
      InputStream input = new BufferedInputStream(url.openStream(), 8192);   
      OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + File.separator + file);  
      byte data[] = new byte[1024];   
      long total = 0; 

      while ((count = input.read(data)) != -1) {      
       total += count;    
       publishProgress((int)((total/lenghtOfFile)*100));        
       output.write(data, 0, count); 

      }   
      output.flush();  
      output.close(); 
      input.close(); 
     } 
     catch(Exception e) 
     {     
      System.out.println("Error: could not connect to host " + decodedLink); 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    protected void onProgressUpdate(Integer... progress) { 
     super.onProgressUpdate(progress);   
     Log.d("progress","values: "+progress[0]); 
     pd.setProgress(progress[0]); 
    } 


    protected void onPostExecute(Void result) { 
     super.onPostExecute(result); 
     pd.dismiss(); 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pd.show(); 
    } 

    @Override 
    protected void onCancelled() { 
     running = false; 
    } 

回答

1

試試這個代碼

希望這會工作。它會告訴你以下下載進度也是如此。

new DownloadFileAsync().execute(fileURL); 

class DownloadFileAsync extends AsyncTask<String, String, String> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      showDialog(DIALOG_DOWNLOAD_PROGRESS); 

     } 

     @Override 
     protected String doInBackground(String... aurl) { 

      try { 
       // connecting to url 
       URL u = new URL(downloadURL); 
       HttpURLConnection c = (HttpURLConnection) u.openConnection(); 
       c.setRequestMethod("GET"); 
       c.setDoOutput(true); 
       c.connect(); 

       // lenghtOfFile is used for calculating download progress 
       int lenghtOfFile = c.getContentLength(); 

       // this is where the file will be seen after the download 
       FileOutputStream f = new FileOutputStream(new File(rootDir 
         + "/my_downloads/", fileName)); 
       // file input is from the url 
       InputStream in = c.getInputStream(); 

       // here's the download code 
       byte[] buffer = new byte[1024]; 
       int len1 = 0; 
       long total = 0; 

       while ((len1 = in.read(buffer)) > 0) { 
        total += len1; // total = total + len1 
        publishProgress("" + (int) ((total * 100)/lenghtOfFile)); 
        f.write(buffer, 0, len1); 

       } 
       f.close(); 

      } catch (Exception e) { 
       Log.d(LOG_TAG, e.getMessage()); 

      } 

      return null; 
     } 

     protected void onProgressUpdate(String... progress) { 
      // Log.d(LOG_TAG,progress[0]); 
      mProgressDialog.setProgress(Integer.parseInt(progress[0])); 
      downloadtext.setText(progress[0] + "%"); 
     } 

     @Override 
     protected void onPostExecute(String unused) { 
      // dismiss the dialog after the file was downloaded 
      dismissDialog(DIALOG_DOWNLOAD_PROGRESS); 

     } 
    } 


@Override 
    protected Dialog onCreateDialog(int id) { 
     switch (id) { 
     case DIALOG_DOWNLOAD_PROGRESS: // we set this to 0 
      mProgressDialog = new ProgressDialog(this); 
      mProgressDialog.setMessage("Downloading file..."); 
      mProgressDialog.setIndeterminate(false); 
      mProgressDialog.setMax(100); 
      mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
      mProgressDialog.setCancelable(true); 
      mProgressDialog.show(); 
      return mProgressDialog; 
     default: 
      return null; 
     } 
    } 

讓我知道如果你需要更多的幫助

感謝 烏默爾

+0

不能使用日誌時,進度[0]顯示負數 –

+0

c.getContentLength()總是返回-1 –

+0

然後它不會得到您的文件大小 –

0

我建議你在你的onProgressUpdate

@Override 
    protected void onProgressUpdate(Integer... progress) { 
     int count = (progress[0]+1); 
     if(FTPDownload.this.isCancelled()) 
     { 
        //Handle the canceling of the AsyncTask Exection 
     } 
else{ 
      pd.setMessage(count+" Of "+mCount+" Downloaded"); 
        pd.show(); 
     } 
+0

沒有,getContentLength()始終顯示-1 –