Android의 비동기 클래스에서 FTP 다운로드에 진행률 표시줄을 표시하는 방법은 무엇입니까? (How to show the progress bar in FTP download in async class in Android?)


문제 설명

Android의 비동기 클래스에서 FTP 다운로드에 진행률 표시줄을 표시하는 방법은 무엇입니까? (How to show the progress bar in FTP download in async class in Android?)

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

(by user120612Bhavik MehtaNaveed Ahmad)

참조 문서

  1. How to show the progress bar in FTP download in async class in Android? (CC BY‑SA 3.0/4.0)

#android-progressbar #FTP #android-asynctask #Android






관련 질문

목록 보기 항목의 보기는 화면에서 보기를 스크롤한 후 원래 상태로 돌아갑니다. (listview item's view returns to original state after scroll the view off the screen)

Android의 비동기 클래스에서 FTP 다운로드에 진행률 표시줄을 표시하는 방법은 무엇입니까? (How to show the progress bar in FTP download in async class in Android?)

Android에서 진행률 표시줄의 ListView (ListView of Progress Bars in android)

안드로이드에서 24시간 SeekBar 또는 ProgressBar를 만드는 방법 (How to create 24hour SeekBar or ProgressBar in android)

Android: ProgressBar가 활동에서 이상하게 보입니다. (Android: ProgressBar looks strange in activity)

Android에서 기본 ProgressDialog 원 색상을 변경하는 방법 (How to change default ProgressDialog circle color in android)

Android: 사이에 공백이 있는 맞춤 원 ProgressBar (Android: Custom circle ProgressBar with spaces in between)

정적 수평 진행률 표시줄 Android (Static horizontal progress bar android)

Android progressBar setVisibility()가 작동하지 않음 (Android progressBar setVisibility() not working)

비동기 작업의 게시 진행률 (Publishing progress in async task)

BaseActvity/BaseFragment의 ProgressBar 관리 (ProgressBar management in BaseActvity/BaseFragment)

진행 중인 경고 대화 상자가 닫히거나 취소되지 않음 (Alertdialog running ongoing dosen't dismiss or cancel)







코멘트