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

橙三吉。 提交于 2019-12-01 11:40:37

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

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...)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!