本文介绍了如何显示在FTP下载进度条在异步类的Andr​​oid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何显示在FTP下载进度条在异步类机器人?

我尝试过很多事情,但没有得到进度条。这是我的code,而我从其他活动调用这个类通过该活动的背景下此类。

 包com.scft;

进口it.sauronsoftware.ftp4j.FTPClient;
进口it.sauronsoftware.ftp4j.FTPDataTransferListener;

进口的java.io.File;

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

公共类ftpdownload_class {

    静态最后弦乐FTP_HOST =**************;

    / ********* FTP用户名*********** /
    静态最后弦乐FTP_USER =*********;

    / ********* FTP密码************ /
    静态最后弦乐FTP_PASS =*******;
      文件fil​​eDownload = NULL;
      长startTime_ftpDownload = 0;
      长endTime_ftpDownload = 0;
      长downloaded_file = 0;
      长startTime_ftpUpload = 0;

      长endTime_ftpUpload = 0;
      FtpClient的客户端= NULL;
        公共静态文件m_fileName;
        私人PopupWindow pwindo;
       串totaltime_ftpUpload,filesize_ftpUpload,ratevalue_ftpUpload,totaltime_ftpDownload,filesize_ftpDownload,ratevalue_ftp_download;
      上下文mContext = NULL;
      公共ftpdownload_class(上下文C)
      {
          mContext = C;
      }
        公共无效ftp_downloadStart(){
            FtpClient的FTP =新FtpClient的();

            尝试 {
                如果(android.os.Build.VERSION.SDK_INT> 9){
                    StrictMode.ThreadPolicy政策=
                            。新StrictMode.ThreadPolicy.Builder()permitAll()建();
                    StrictMode.setThreadPolicy(政策);
                }

                ftp.connect(FTP_HOST,158); // 158是端口号
                //System.out.println(ftp.connect(host)[0]);
                ftp.login(FTP_USER,FTP_PASS);
                fileDownload =新的文件(/ SD卡/请将test.mp3);
                fileDownload.createNewFile();

                startTime_ftpDownload = System.currentTimeMillis的();

                ftp.download(请将test.mp3,fileDownload,
                        新FTPDataTransferListener(){

                    // lenghtOfFile = conection.getContentLength();

                    公共无效转移(INT为arg0){
                       // download_btn.setVisibility(View.GONE);
                        //Log.v("log_tag,这是为转移);
                       // Toast.makeText(getBaseContext(),转移...+ arg0中,Toast.LENGTH_SHORT).show();
                    }

                    公共无效启动(){

                        // TODO自动生成方法存根
                       // Toast.makeText(getBaseContext(),下载开始......,Toast.LENGTH_SHORT).show();
                        //Log.v("log_tag,这是一个开始);
                    }

                    公共无效失败(){
                       // download_btn.setVisibility(View.VISIBLE);
                        Toast.makeText(mContext,失败了......,Toast.LENGTH_SHORT).show();
                        的System.out.println(失败......);
                    }

                    公共无效结束(){

                       // download_btn.setVisibility(View.VISIBLE);

                        endTime_ftpDownload = System.currentTimeMillis的(); //有可能

                        Toast.makeText(mContext,下载完成......,Toast.LENGTH_SHORT).show();

                        getspeedfor_ftp_download();
                        //Log.v("log_tag,这是完成);



                    }

                    公共无效中止(){
                       // download_btn.setVisibility(View.VISIBLE);
                        Toast.makeText(mContext,转让中止,请再试一次......,Toast.LENGTH_SHORT).show();
                        //Log.v("log_tag,这是中止);

                    }
                });

            }赶上(例外五){
                e.printStackTrace();
                尝试 {
                    ftp.disconnect(真正的);
                }赶上(例外E2){
                    e2.printStackTrace();
                }
            }


        }

           长downloaded_file_ftp = 0;
     公共无效getspeedfor_ftp_download()
        {

            downloaded_file_ftp = fileDownload.length();

            //Log.d("D​​ownloadManager,下载结束:+((endTime的 - 的startTime)/ 1000)+秒);
            串ABC =(((endTime_ftpDownload  -  startTime_ftpDownload)/ 1000)+秒);
            totaltime_ftpDownload = ABC;

            双尺寸=(downloaded_file_ftp / 1024);
            如果(大小和LT 1000)
                filesize_ftpDownload =将String.valueOf(尺寸).concat(KB);
            其他
                filesize_ftpDownload =将String.valueOf(尺寸/ 1024).concat(MB);

            双倍速率=(((downloaded_file_ftp / 1024)/((endTime_ftpDownload  -  startTime_ftpDownload)/ 1000))* 8);
            率= Math.round(率* 100.0)/ 100.0;

            如果(速率GT; ​​1000)
                ratevalue_ftp_download =将String.valueOf(速度/ 1024).concat(Mbps的);
            其他
                ratevalue_ftp_download =将String.valueOf(率).concat(Kbps的);
            Log.d(下载管理器,下载速度:+ ratevalue_ftp_download);


            alertStatus_ftp_download();
        }

        公共无效alertStatus_ftp_download()
          {

                AlertDialog.Builder alertDialogBu​​ilderfor_ftp_download =新AlertDialog.Builder(mContext);

                //设置标题
                alertDialogBu​​ilderfor_ftp_download.setTitle(FTP下载速度状态);

                //设置对话框消息
                alertDialogBu​​ilderfor_ftp_download
                .setMessage(下载速度:+ ratevalue_ftp_download +,+\ñ总文件大小:+ filesize_ftpDownload +\ n总计花费时间:+ totaltime_ftpDownload)
                    //.setMessage("Download速度+ ratevalue_ftp_download)
                    .setCancelable(假)
                    .setPositiveButton(OK,新DialogInterface.OnClickListener(){
                        公共无效的onClick(DialogInterface对话框,INT ID){
                            //如果单击此按钮,关闭
                            //当前活动
                            dialog.cancel();
                        }
                      })
                    .setNegativeButton(取消,新DialogInterface.OnClickListener(){
                        公共无效的onClick(DialogInterface对话框,INT ID){
                            //如果单击此按钮,只需关闭
                            //对话框并做什么
                            dialog.cancel();
                        }
                    });

                    //创建警报对话框
                    AlertDialog alertDialogftp_download = alertDialogBu​​ilderfor_ftp_download.create();

                    // 展示下
                    alertDialogftp_download.show();
                }
}
 

解决方案

搜索几个小时后,我终于建成了这样一个解决方案。创建一个提供者类这样的UploadToFtp.java

 公共类UploadToFtp {
        公共FtpClient的mFTPClient = NULL;
        字符串主机;
        字符串的用户名;
        字符串密码;
        CopyStreamAdapter streamListener;
        ProgressDialog pDialog;
        布尔值状态= FALSE;

        公共布尔ftpUpload1(字符串srcFilePath,字符串desFileName,

        字符串desDirectory,字符串主机,字符串username,字符串密码,
                最后ProgressDialog pDialog){
            this.pDialog = pDialog;

            this.host =主机;
            this.username =用户名;
            this.password =密码;
            INT端口= 21;
            mFTPClient =新FtpClient的();

            尝试 {
                mFTPClient.connect(主机,端口); //连接主机
                mFTPClient.login(用户名,密码); //验证使用用户名
                                                        //和密码
                mFTPClient.changeWorkingDirectory(desDirectory); //改变目录
                的System.out.println(目的地指南 - >中+ desDirectory); //该
                // 目录
                //其中,图像
                // 会是
                //上传
                mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);

                的BufferedInputStream buffIn = NULL;
                最终文件的文件=新的文件(srcFilePath);

                的System.out.println(要去文件 - >中+ srcFilePath);
                buffIn =新的BufferedInputStream(新的FileInputStream(文件),8192);

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

                    @覆盖
                    公共无效bytesTransferred(长totalBytesTransferred,
                            INT bytesTransferred,长streamSize){
                        //此方法将每次有的叫
                        //字节传输
                        //的System.out.println(流大小+ file.length());
                        //的System.out.println(字节transfeedd
                        // + totalBytesTransferred);

                        INT百分比=(INT)(totalBytesTransferred * 100 /文件
                                。长度());
                        pDialog.setProgress(百分比);

                        如果(totalBytesTransferred == file.length()){
                            的System.out.println(100%转移);

                            removeCopyStreamListener(streamListener);

                        }

                    }

                };
                mFTPClient.setCop​​yStreamListener(streamListener);

                状态= mFTPClient.storeFile(desFileName,buffIn);
                的System.out.println(状态值 - >中+状态);
                buffIn.close();
                mFTPClient.logout();
                mFTPClient.disconnect();
            }赶上(例外五){
                e.printStackTrace();
            }

            返回状态;
        }
    }
 

现在做出的AsyncTask在类文件的地方实际上是被提取或正在创建,像这样

 类UploadTask扩展的AsyncTask<太虚,整型,太虚> {
        ProgressDialog pDialog;
        布尔uploadStat;
        UploadToFtp UTP =新UploadToFtp();

        @覆盖
        在preExecute保护无效(){
            pDialog =新ProgressDialog(UploadActivity.this);
            pDialog.setMessage(上传...);
            pDialog.setCancelable(假);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.show();

            super.on preExecute();
        }

        @覆盖
        保护无效doInBackground(虚空...... PARAMS){
            的System.out.println(源URL  - >中+ sourceUrl);
            的System.out.println(文件名 - >中+文件名);
            的System.out.println(desDirectory  - >中+ desDirectory);
            uploadStat =新UploadToFtp()。ftpUpload1(sourceUrl,文件名,
                    desDirectory,app.getHostname(),app.getUsername(),
                    app.getPassword(),pDialog);
            runOnUiThread(新的Runnable(){
                @覆盖
                公共无效的run(){
                    如果(uploadStat){
                        如果(pDialog =空&安培;!&安培; pDialog.isShowing()){
                            pDialog.dismiss();
                        }
                        reviewImageView.setImageBitmap(空);
                        mCurrentPhotoPath =;
                        照片= NULL;
                        uploadMessage.setVisibility(View.VISIBLE);
                        UploadSuccess.setVisibility(View.VISIBLE);
                    } 其他 {
                        AlertDialog.Builder alertDialog =新AlertDialog.Builder(
                                UploadActivity.this);

                        //设置对话框消息
                        alertDialog.setTitle(错误上传文件);
                        alertDialog
                                .setMessage(连接上传过程中丢失,请重试!);
                        alertDialog.setCancelable(假);
                        //设置图标,以对话框

                        //设置OK按钮
                        alertDialog.setPositiveButton(OK,
                                新DialogInterface.OnClickListener(){
                                    公共无效的onClick(DialogInterface对话框,
                                            INT编号){
                                        dialog.cancel();
                                    }
                                });
                        alertDialog.show();
                    }
                }
            });
            返回null;
        }

        @覆盖
        保护无效onPostExecute(无效的结果){
            如果(pDialog =空&安培;!&安培; pDialog.isShowing()){
                pDialog.dismiss();
            }
            的System.out.println(结果 - >中+的结果);
            super.onPostExecute(结果);
        }
    }
 

现在只需拨打该AsyncTask的按钮点击,或者你想要的任何其它事件

 新UploadTask()执行()。
 

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();
                }
}
解决方案

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

这篇关于如何显示在FTP下载进度条在异步类的Andr​​oid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 22:34