2013-07-10 189 views
0

所有有可能創建一個進度對話框來顯示線程下的上傳進度,我使用這段代碼上傳一個名爲index.html的文件爲ftp。 請提前幫助我thanx。將進度對話框添加到storefile();

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

回答

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

+0

我想上傳一個文件不下載 –

+0

從android 1.6開始,最多可以有5個併發的asynctasks – SemaphoreMetaphor

+0

請給我一個上傳文件的代碼,不要下載進度條, thanx回答 –