将进度对话框添加到storefile();

时间:2013-07-10 06:29:49

标签: java android ftp-client uploading

所有可以创建进度对话框以显示线程下的上传进度我使用此代码将名为index.html的文件上传到ftp。 请提前帮助我。

new Thread(new Runnable() {

  public void run() {
    Looper.prepare();

    FTPClient client = new FTPClient();
    try {  
      boolean  result = false;
      FileInputStream fis = null;
      client.connect(server);
      client.enterLocalPassiveMode();
      client.login(user, pass);
      client.makeDirectory("/public_html/"+str);
      client.setFileType(FTP.BINARY_FILE_TYPE);
      client.setFileTransferMode(FTP.BINARY_FILE_TYPE );
      client.changeWorkingDirectory(str);
      String path1 =      Environment.getExternalStorageDirectory() + "/index.htm";
      File f = new File(path1);
      String testname = "/public_html/"+str+"/"+f.getName();

      fis = new 
          FileInputStream(f);
      result = client.storeFile(testname, fis);


      if (result == true){
        Log.v("upload","upload successfull");

      }
      else{
        Log.v("upload", "upload failed");

      }
      client.logout();
      client.disconnect();
    } 
    catch (Exception e) {
      Context context = getApplicationContext();
      CharSequence text = "failed!!";
      int duration = Toast.LENGTH_SHORT;

      Toast toast = Toast.makeText(context, text, duration);
      toast.show();
    }
  }


}).start();

1 个答案:

答案 0 :(得分:0)

为什么不使用asynctask?有了它你可以在onPreExecute方法中产生一个对话,而不是在onProgressUpdate方法中更新后台任务的进度...还有其他方法可以做到这一点,但我相信这是最干净,最简单的

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }
}

android dev参考应该有助于清除http://developer.android.com/reference/android/os/AsyncTask.html