2011-05-18 54 views
0

我正在製作一個Android應用程序,用戶可以從FTP服務器下載文件。對於ftp部分,我使用apache.org.commons-net軟件包。下載文件時Android應用程序不規則地凍結

當我連接到服務器時,我得到一個文件名列表,然後我想下載每個文件。我開始在它自己的一個線程中運行的下載例程。

我遇到的問題是,如果我在服務器上說6個文件,並且在我的模擬器上運行此代碼,它會下載前兩個文件,然後凍結(進度條掛在34%)。當我在手機上運行它時,它會下載三個文件並凍結。

如果我通過模擬器上的代碼調試我的方式,它會下載所有六個文件就好,不會凍結。

有沒有人有任何想法可能是什麼問題?

由於提前, LordJesus

這是我的代碼(客戶端已經初始化):

private void downloadFiles2() { 
    dialog = new ProgressDialog(this); 
    dialog.setCancelable(true); 
    dialog.setMessage("Loading..."); 
    // set the progress to be horizontal 
    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
    // reset the bar to the default value of 0 
    dialog.setProgress(0); 
    dialog.setMax(DownloadCount); 
    // display the progressbar 
    dialog.show(); 

    // create a thread for updating the progress bar 
    Thread background = new Thread (new Runnable() { 
     public void run() { 
      InputStream is = null; 
      try { 
       for (String filename : fileNames) { 
        is = client.retrieveFileStream(filename); 
        byte[] data = new byte[1024]; 
        int x = 0; 
        x = is.read(data, 0, 1024); 
        boolean downloadIsNewer = true; 
        File fullPath = new File(path + "/" + filename); 
        Log.d("FTP", "Starting on " + filename); 
        if (fullPath.exists()) { 
         downloadIsNewer = checkIfNewer(data, fullPath); 
        } 

        if (downloadIsNewer) { 
         Log.d("FTP", "Need to download new file"); 
         FileOutputStream fos = new FileOutputStream(fullPath); 
         fos.write(data,0,x); 
         while((x=is.read(data,0,1024))>=0){ 
          fos.write(data,0,x); 
         } 
         fileText += filename + " - downloaded OK." + FileParser.newline; 
         is.close(); 
         client.completePendingCommand(); 
         fos.flush(); 
         fos.close();       
        } 
        else { 
         Log.d("FTP", "No need to download"); 
         is.close(); 
         fileText += filename + " - own copy is newer." + FileParser.newline; 
        } 
        // active the update handler 
        progressHandler.sendMessage(progressHandler.obtainMessage()); 
       } 
       client.logout(); 
       client.disconnect(); 
      } 

      catch (Exception e) { 
       // if something fails do something smart 
      } 
     } 
    }); 
    // start the background thread 
    background.start(); 
} 

Handler progressHandler = new Handler() { 
    public void handleMessage(Message msg) { 
     dialog.incrementProgressBy(1); 
     InfoTextView.setText(fileText); 
     if(dialog.getProgress()== dialog.getMax()) 
     { 

      dialog.dismiss(); 
     } 
    } 
}; 

回答

0

OK,發現了問題:

當布爾downloadIsNewer是假的我不要調用client.completePendingCommand()。當我在這行之前添加那個.close()它就像一個魅力。