How to show the progress bar in FTP download in as

2019-03-01 11:59发布

问题:

How to show the progress bar in FTP download in async class in android?

I've tried many things but didn't get the progress bar. Here's my code, and I'm calling this class from other Activity passing the context of that activity to this class.

package com.scft;

import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;

import java.io.File;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.StrictMode;
import android.util.Log;
import android.widget.PopupWindow;
import android.widget.Toast;

public class ftpdownload_class {

    static final String FTP_HOST= "**************";

    /*********  FTP USERNAME ***********/
    static final String FTP_USER = "*********";

    /*********  FTP PASSWORD ***********/
    static final String FTP_PASS  ="*******";
      File fileDownload=null;
      long startTime_ftpDownload=0;
      long endTime_ftpDownload=0;
      long downloaded_file=0;
      long startTime_ftpUpload=0;

      long endTime_ftpUpload=0;
      FTPClient client=null;
        public static File m_fileName;
        private PopupWindow pwindo;
       String  totaltime_ftpUpload,filesize_ftpUpload,ratevalue_ftpUpload,totaltime_ftpDownload,filesize_ftpDownload,ratevalue_ftp_download;
      Context mContext=null;
      public ftpdownload_class( Context c)
      {
          mContext=c;
      }
        public void ftp_downloadStart() {
            FTPClient ftp = new FTPClient();

            try {
                if (android.os.Build.VERSION.SDK_INT > 9) {
                    StrictMode.ThreadPolicy policy = 
                            new StrictMode.ThreadPolicy.Builder().permitAll().build();
                    StrictMode.setThreadPolicy(policy);
                }

                ftp.connect(FTP_HOST,158);//158 is the port number
                //System.out.println(ftp.connect(host)[0]);
                ftp.login(FTP_USER, FTP_PASS);
                fileDownload = new File("/sdcard/test.mp3");
                fileDownload.createNewFile();

                startTime_ftpDownload = System.currentTimeMillis();

                ftp.download("test.mp3", fileDownload,
                        new FTPDataTransferListener() {

                    // lenghtOfFile = conection.getContentLength();

                    public void transferred(int arg0) {
                       // download_btn.setVisibility(View.GONE);
                        //Log.v("log_tag", "This is for transfer");
                       // Toast.makeText(getBaseContext(), " transferred ..."+arg0 , Toast.LENGTH_SHORT).show();
                    }

                    public void started() {

                        // TODO Auto-generated method stub
                       // Toast.makeText(getBaseContext(), " Download Started ...", Toast.LENGTH_SHORT).show();
                        //Log.v("log_tag", "This is for started");
                    }

                    public void failed() {
                       // download_btn.setVisibility(View.VISIBLE);
                        Toast.makeText(mContext, "  failed ...", Toast.LENGTH_SHORT).show();
                        System.out.println(" failed ..." );
                    }

                    public void completed() {

                       // download_btn.setVisibility(View.VISIBLE);

                        endTime_ftpDownload = System.currentTimeMillis(); //maybe

                        Toast.makeText(mContext, " Download completed ...", Toast.LENGTH_SHORT).show();

                        getspeedfor_ftp_download();
                        //Log.v("log_tag", "This is for completed");



                    }

                    public void aborted() {
                       // download_btn.setVisibility(View.VISIBLE);
                        Toast.makeText(mContext," transfer aborted,please try again...", Toast.LENGTH_SHORT).show();
                        //Log.v("log_tag", "This is for aborted");

                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
                try {
                    ftp.disconnect(true);    
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }


        }

           long downloaded_file_ftp=0;
     public void getspeedfor_ftp_download()
        {

            downloaded_file_ftp = fileDownload.length();

            //Log.d("DownloadManager", "download ended: " + ((endTime - startTime) / 1000) + " secs");
            String abc = (((endTime_ftpDownload - startTime_ftpDownload) / 1000) + " secs");
            totaltime_ftpDownload = abc;

            double size = (downloaded_file_ftp/1024);
            if(size<1000)
                filesize_ftpDownload=String.valueOf(size).concat("Kb");
            else
                filesize_ftpDownload=String.valueOf(size/1024).concat("Mb");

            double rate = (((downloaded_file_ftp / 1024) / ((endTime_ftpDownload - startTime_ftpDownload) / 1000)) * 8);
            rate = Math.round( rate * 100.0 ) / 100.0;

            if(rate > 1000)
                ratevalue_ftp_download = String.valueOf(rate / 1024).concat(" Mbps");
            else
                ratevalue_ftp_download = String.valueOf(rate).concat(" Kbps"); 
            Log.d("DownloadManager", "download speed: "+ratevalue_ftp_download); 


            alertStatus_ftp_download();
        }

        public void alertStatus_ftp_download()
          {

                AlertDialog.Builder alertDialogBuilderfor_ftp_download = new AlertDialog.Builder(mContext);

                // set title
                alertDialogBuilderfor_ftp_download.setTitle("Ftp Download Speed Status");

                // set dialog message
                alertDialogBuilderfor_ftp_download
                .setMessage("Download Speed : "+ratevalue_ftp_download+",  "+"\n Total File Size  :"+filesize_ftpDownload+"\nTotal time taken :   "+totaltime_ftpDownload)
                    //.setMessage("Download Speed  "+ratevalue_ftp_download)    
                    .setCancelable(false)
                    .setPositiveButton("Ok",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, close
                            // current activity
                            dialog.cancel();
                        }
                      })
                    .setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, just close
                            // the dialog box and do nothing
                            dialog.cancel();
                        }
                    });

                    // create alert dialog
                    AlertDialog alertDialogftp_download = alertDialogBuilderfor_ftp_download.create();

                    // show it
                    alertDialogftp_download.show();
                }
}

回答1:

After searching hours and hours, i finally built a solution like this. Create an Uploader class like this UploadToFtp.java

public class UploadToFtp {
        public FTPClient mFTPClient = null;
        String host;
        String username;
        String password;
        CopyStreamAdapter streamListener;
        ProgressDialog pDialog;
        boolean status = false;

        public boolean ftpUpload1(String srcFilePath, String desFileName,

        String desDirectory, String host, String username, String password,
                final ProgressDialog pDialog) {
            this.pDialog = pDialog;

            this.host = host;
            this.username = username;
            this.password = password;
            int port = 21;
            mFTPClient = new FTPClient();

            try {
                mFTPClient.connect(host, port); // connecting to the host
                mFTPClient.login(username, password); // Authenticate using username
                                                        // and password
                mFTPClient.changeWorkingDirectory(desDirectory); // change directory
                System.out.println("Dest Directory-->" + desDirectory); // to that
                // directory
                // where image
                // will be
                // uploaded
                mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);

                BufferedInputStream buffIn = null;
                final File file = new File(srcFilePath);

                System.out.println("on going file-->" + srcFilePath);
                buffIn = new BufferedInputStream(new FileInputStream(file), 8192);

                mFTPClient.enterLocalPassiveMode();
                streamListener = new CopyStreamAdapter() {

                    @Override
                    public void bytesTransferred(long totalBytesTransferred,
                            int bytesTransferred, long streamSize) {
                        // this method will be called everytime some
                        // bytes are transferred
                        // System.out.println("Stream size" + file.length());
                        // System.out.println("byte transfeedd "
                        // + totalBytesTransferred);

                        int percent = (int) (totalBytesTransferred * 100 / file
                                .length());
                        pDialog.setProgress(percent);

                        if (totalBytesTransferred == file.length()) {
                            System.out.println("100% transfered");

                            removeCopyStreamListener(streamListener);

                        }

                    }

                };
                mFTPClient.setCopyStreamListener(streamListener);

                status = mFTPClient.storeFile(desFileName, buffIn);
                System.out.println("Status Value-->" + status);
                buffIn.close();
                mFTPClient.logout();
                mFTPClient.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }

            return status;
        }
    }

Now make an Asynctask in the class where file is actually being fetched or being created, like this

class UploadTask extends AsyncTask<Void, Integer, Void> {
        ProgressDialog pDialog;
        Boolean uploadStat;
        UploadToFtp utp = new UploadToFtp();

        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(UploadActivity.this);
            pDialog.setMessage("Uploading...");
            pDialog.setCancelable(false);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.show();

            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            System.out.println("source url -> " + sourceUrl);
            System.out.println("filename -> " + filename);
            System.out.println("desDirectory -> " + desDirectory);
            uploadStat = new UploadToFtp().ftpUpload1(sourceUrl, filename,
                    desDirectory, app.getHostname(), app.getUsername(),
                    app.getPassword(), pDialog);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (uploadStat) {
                        if (pDialog != null && pDialog.isShowing()) {
                            pDialog.dismiss();
                        }
                        reviewImageView.setImageBitmap(null);
                        mCurrentPhotoPath = "";
                        photo = null;
                        uploadMessage.setVisibility(View.VISIBLE);
                        UploadSuccess.setVisibility(View.VISIBLE);
                    } else {
                        AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                                UploadActivity.this);

                        // Setting Dialog Message
                        alertDialog.setTitle("Error Uploading File");
                        alertDialog
                                .setMessage("Connection lost during upload, please try again!");
                        alertDialog.setCancelable(false);
                        // Setting Icon to Dialog

                        // Setting OK Button
                        alertDialog.setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        dialog.cancel();
                                    }
                                });
                        alertDialog.show();
                    }
                }
            });
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            if (pDialog != null && pDialog.isShowing()) {
                pDialog.dismiss();
            }
            System.out.println("Result-->" + result);
            super.onPostExecute(result);
        }
    }

Now simply call this Asynctask on button click or any other event you want

new UploadTask().execute();


回答2:

You can do something like this..

public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DOWNLOAD_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("waiting 5 minutes..");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
        return mProgressDialog;
    default:
    return null;
    }
}

Then write an async task to update progress..

private class DownloadZipFileTask extends AsyncTask<String, String, String> {

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

    @Override
    protected String doInBackground(String... urls) {
        //Copy you logic to calculate progress and call
        publishProgress("" + progress);
        //Your code Here
    }

    protected void onProgressUpdate(String... progress) {        
    mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String result) {           
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }
}

This is the Procedure to use Progress Dialog update with the AsyncTask, write your code in doInBackground(String...)