0

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

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();
4

1 回答 1

0

为什么不使用异步任务?有了它,您可以在 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

于 2013-07-10T06:37:39.630 回答