0

当我尝试使用 FTP 从服务器下载文件时遇到问题。我需要显示下载文件的搜索栏状态和互联网的下载速度。我能够显示 HTTP 的搜索栏状态和 Internet 速度,但对于 FTP,我无法执行相同的任务。在下面的附图中,我需要显示 FTP 和 HTTP 的搜索栏和网络速度。下面是我用于 HTTP 和 FTP 的源代码。我不知道我错过了哪里?

在此处输入图像描述

HTTP 代码:

    class DownloadFileAsync extends AsyncTask<String, String, String> {     //see the summary of asyncTask

        long duration, pk;
        private boolean sleep = false;
        private HashMap<String, Object> map;
        private ProgressBar bar;
        private TextView real_time, test_avg, peak, status;
        private ImageView pp;

        //constructor
        public DownloadFileAsync(HashMap<String, Object> map) {
            this.map = map;
            bar = (ProgressBar) map.get("bar");
            // trans = (TextView) map.get("trans");
            //real_time = (TextView) map.get("real_time");
            test_avg = (TextView) map.get("test_avg");
            //peak = (TextView) map.get("peak");
            status = (TextView) map.get("status");
            pp = (ImageView) map.get("pp");
        }

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

        @Override
        protected String doInBackground(String... aurl) {
            int count = 0;
            try {
                updateUI(pp, R.drawable.pause);
                updateUI(status, "Connecting");
                URL url = new URL(map.get("url").toString());
                URLConnection conexion = url.openConnection();
                conexion.connect();

                final int lenghtOfFile = conexion.getContentLength();
                InputStream input = new BufferedInputStream(url.openStream());
                updateUI(status, "Connected");
                OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()
                                    + File.separator
                                    + Info.getInfo(con).HTTP_DOWNLOAD_FILE_NAME);
                byte data[] = new byte[1024];
                long total = 0;
                final long started = System.currentTimeMillis();
                long sleepingTime= 0;
                System.out.println("started time --"+started);
                updateUI(status, "Downloading");
                while ((count = input.read(data)) != -1) {
                    while (sleep) {
                        Thread.sleep(1000);
                        sleepingTime +=1000;
                    }
                    total += count;
                    final int progress = (int) ((total * 100) / lenghtOfFile);
                    final long speed = total;
                    duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
                    runOnUiThread(new Runnable() {
                        public void run() {
                            bar.setProgress(progress);
                            // trans.setText("" + progress);
                            //duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;

                            //real_time.setText(duration + " secs");
                            if (duration != 0) {
                                test_avg.setText((speed / duration) / 1024 + " kbps");
                                if (pk <= (speed / duration) / 1024)
                                {
                                    pk = (speed / duration) / 1024;
                                }
                                //peak.setText(pk + " kbps");
                            }
                        }
                    });
                    output.write(data, 0, count);
                }
                output.flush();
                output.close();
                input.close();
                updateUI(status, "Success");
            } 
            catch (final Exception e) {
                e.printStackTrace();
                updateUI(status, "Failed");
            }
            updateUI(pp, R.drawable.resume);
            return null;
        }

        private void updateUI(final TextView tv, final String str) {
            runOnUiThread(new Runnable() {
                public void run() {
                    tv.setText(str);
                }
            });
        }

        private void updateUI(final ImageView iv, final int id) {                   // may create problem
            runOnUiThread(new Runnable() {
                public void run() {
                    iv.setImageResource(id);
                }
            });
        }

        public void gotosleep(boolean val) {
            sleep = val;
        }

        public boolean areYouSleeping() {
            return sleep;
        }

        @Override
        protected void onPostExecute(String unused) {

            try {
                //System.out.println("Info.getInfo(con).data.indexOf(map)==="+Info.getInfo(con).data.indexOf(map)+"   map  "+map);
                if (!PARALLEL_MODE       //for sequence mode
                        && (Info.getInfo(con).data.indexOf(map) + 1) <= Info.getInfo(con).data.size() 
                        && testRunning) {
                    /*System.out.println("Info.getInfo(con).data.indexOf(map) + 1 "+Info.getInfo(con).data.indexOf(map) + 1
                            +"   Info.getInfo(con).data.size()   "+Info.getInfo(con).data.size()+" testRunning   "+testRunning);
                    System.out.println("Info.getInfo(con).data.indexOf(map)==="+Info.getInfo(con).data.indexOf(map)+"   map  "+map);*/


                    System.out.println("asynclist   "+asynclist.size());
                    asynclist.remove(0);    //asynclist contains objects of (downloadAsync(map))
                    if(asynclist.size() > 0){

                        System.out.println("tlist in post execute+++"+tlist);
                        //DownloadFileAsync dfa = new DownloadFileAsync(tlist.get(0));
                        DownloadFileAsync dfa = (DownloadFileAsync) asynclist.get(0);
                        dfa.execute();
                        tlist.remove(0);
                    }
                    else{
                        startTests();
                    }
                } 
                else if (PARALLEL_MODE   && stopCount < asynclist.size() && testRunning) {  //for parallel mode
                    System.out.println("stopCount before condition= " + stopCount);
                    if (stopCount == asynclist.size() -1 && testRunning) {
                        System.out.println("stopCount inside 1st condition= " + stopCount);
                        stopCount = 0;
                        // stopTests(0);
                        startTests();
                        System.out.println("Tests Started");
                    } 
                    else {
                        stopCount++;
                        System.out.println("stopCount after increment = " + stopCount);
                        ;
                    }
                }
            } 
            catch (Exception ed) {
                ed.printStackTrace();
                go.setText(R.string.go);
                //testRunning = false;
            }
        }
    }

For FTP:--

class FTPAsync extends AsyncTask<String, String, String> {
        //private int mode = -1;
        //added
        long duration, pk;
        private boolean sleep1 = false;
        private HashMap<String, Object> map;
        private ProgressBar bar;
        private TextView real_time, test_avg, peak, status;
        private ImageView pp;
        //
        public FTPAsync(int mode) {
            //  this.mode = mode;
        }

        //added
        public FTPAsync(HashMap<String, Object> map) {
            //Toast.makeText(con, "ftpAsync constructer is called" ,Toast.LENGTH_SHORT).show();
            this.map = map;
            bar = (ProgressBar) map.get("bar");
            // trans = (TextView) map.get("trans");
            //real_time = (TextView) map.get("real_time");
            test_avg = (TextView) map.get("test_avg");
            //peak = (TextView) map.get("peak");
            status = (TextView) map.get("status");
            pp = (ImageView) map.get("pp");
        }

        //
        @Override
        protected void onPreExecute() {
            //Toast.makeText(con, "onPreExecute() is called" ,Toast.LENGTH_SHORT).show();
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... arg0) {
            int count = 0;
            FTPClient ObjFtpCon = new FTPClient();
            //Toast.makeText(con, "FTPasync doInBackground() is called" ,Toast.LENGTH_SHORT).show();
            try {
                runOnUiThread(new Runnable() {
                    public void run() {

                        bar.setProgress(0);
                        //real_time.setText(0 + " secs");
                        //test_avg.setText(0+ " kbps");                     
                        //peak.setText(0+" kbps");
                    }
                });
                updateUI(pp, R.drawable.pause);
                //ObjFtpCon.connect("ftp.customhdclips.com");
                ObjFtpCon.connect("ftp."+map.get("url").toString());
                updateUI(status, "Connecting");

                //if (ObjFtpCon.login("fstech@customhdclips.com", "fstech123")) {
                if (ObjFtpCon.login(map.get("username").toString(), map.get("password").toString())) {  
                    updateUI(status, "Connected");
                    // toast("Connected to FTP Server : ftp.customhdclips.com");
                    ObjFtpCon.enterLocalPassiveMode(); // important!
                    ObjFtpCon.cwd("/");// to send the FTP CWD command to the server, receive the reply, and return the reply code. 


                    //if (mode == 0) {
                    if(Integer.parseInt((map.get("oprn").toString()))== 0){ 
                        // Download
                        System.out.println("download test is called");
                        File objfile = new File(
                                Environment.getExternalStorageDirectory()
                                + File.separator + "/logo.png");



                        objfile.createNewFile();
                        FileOutputStream objFos = new FileOutputStream(objfile);
                        boolean blnresult = ObjFtpCon.retrieveFile("/logo.png",
                                objFos);
                        objFos.close();
                        if (blnresult) {
                            // toast("Download succeeded");
                            // toast("Stored at : " +
                            // objfile.getAbsolutePath());
                        }



                    } 

                    else {
                        // Upload
                        System.out.println("upload test is called");
                        //Toast.makeText(con, "upload FTP test is called", Toast.LENGTH_SHORT).show();
                        //ContextWrapper context = null;
                        //assetManager= context.getAssets();

                        assetManager = getResources().getAssets();
                        input1 = assetManager.open("hello.txt");

                        final long started = System.currentTimeMillis();
                        int size = input1.available();
                        //byte[] buffer = new byte[size];
                        byte dataByte[] = new byte[1024];
                        //input1.read(buffer);

                        //String data = "ZK DATA TESTER TEST DATA1sdfsdf";
                        String data = input1.toString();
                        System.out.println("dat value is........"+data);
                        final int lenghtOfFile = data.getBytes().length;
                        //final int lenghtOfFile = input1.getBytes().length;
                        System.out.println("length of file....."+lenghtOfFile);
                        ByteArrayInputStream in = new ByteArrayInputStream(
                                data.getBytes());

                        //toast("Uploading /test.txt"); 
                        //Toast.makeText(con,"File Size : " +data.getBytes().length + " bytes",Toast.LENGTH_SHORT).show();
                        //byte b[] = new byte[1024];

                        long total = 0;
                        long sleepingTime= 0;
                        System.out.println("started time --"+started);
                        updateUI(status, "Uploading");
                        while ((count = in.read(dataByte)) != -1)
                        {   
                            System.out.println("read value is...."+in.read(dataByte));
                            while (sleep1) {
                                Thread.sleep(1000);
                                System.out.println("ftp upload is in sleeping mode");
                                sleepingTime +=1000;    
                            }
                            System.out.println("Total count --"+count);
                            total += count;

                            System.out.println("Only Total --"+total);

                            final int progress = (int) ((total * 100) / lenghtOfFile);
                            final long speed = total;
                            //duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;

                            boolean result = ObjFtpCon.storeFile("/test.txt", input1);
                            //boolean result = ObjFtpCon.storeFile(map.get("file_address").toString()+"/test.txt", input1);

                            duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
                            runOnUiThread(new Runnable() {
                                public void run() {

                                    bar.setProgress(progress);
                                    // trans.setText("" + progress);
                                    //duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
                                    //duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;  
                                    //real_time.setText(duration + " secs");
                                    if (duration != 0) {
                                        test_avg.setText((((speed / duration)*1000)*0.0078125)
                                                + " kbps");
                                        /*if (pk <= (speed / duration) / 1024) {
                                        pk = (speed / duration) / 1024;
                                    }*/
                                        if (pk <= ((speed / duration)*1000)*0.0078125) {
                                            pk = (long)(((speed / duration)*1000)*0.0078125);
                                        }
                                        //peak.setText(pk + " kbps");
                                    }
                                }
                            });
                            //in.close();
                            if (result) {
                                updateUI(status, "Uploaded");
                                // toast("Uploading succeeded");
                                // toast("Uploaded at /test.txt");
                                //duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
                                System.out.println("curreent time..... "+System.currentTimeMillis());
                                System.out.println("started time --"+started);
                                System.out.println("sleep tome...."+sleepingTime);
                                System.out.println("duration is....."+duration);
                                /*runOnUiThread(new Runnable() {
                                public void run() {
                                    bar.setProgress(progress);
                                    // trans.setText("" + progress);
                                    //duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;

                                    real_time.setText(duration + " secs");
                                    if (duration != 0) {
                                        test_avg.setText((speed / duration) / 1024
                                                + " kbps");
                                        if (pk <= (speed / duration) / 1024) {
                                            pk = (speed / duration) / 1024;
                                        }
                                        peak.setText(pk + " kbps");
                                    }
                                }
                            });*/
                            }
                            /*while(!result){Thread.sleep(1000);}*/
                        }
                        in.close();
                    }
                }



                else{
                    System.out.println("password entered is incorrect");
                    //Toast.makeText(con, "Username or/and password is incorrect", Toast.LENGTH_SHORT).show();
                }
            } 
            catch (Exception e) {
                e.printStackTrace();
                // toast(e.getLocalizedMessage());
            }

            try {
                ObjFtpCon.logout();
                ObjFtpCon.disconnect();
            } 
            catch (IOException e) {
                e.printStackTrace();
                // toast(e.getLocalizedMessage());
            }
            return null;
        }

        @override
        protected void onPostExecute(String unused) {
            try {
                //System.out.println("Info.getInfo(con).data.indexOf(map)==="+Info.getInfo(con).data.indexOf(map)+"   map  "+map);
                if (!PARALLEL_MODE       //for sequence mode
                        && (Info.getInfo(con).data.indexOf(map) + 1) <= Info.getInfo(con).data.size() 
                        && testRunning) {



                    System.out.println("ftpasynclist   "+ftpasynclist.size());
                    ftpasynclist.remove(0);    //asynclist contains objects of (FTPAsync(map))
                    if(ftpasynclist.size() > 0){

                        System.out.println("tlist in post execute+++"+ftplist);
                        //DownloadFileAsync dfa = new DownloadFileAsync(tlist.get(0));
                        FTPAsync dfa = (FTPAsync)ftpasynclist.get(0);
                        dfa.execute();
                        ftplist.remove(0);
                    }
                    else{
                        startTests();
                    }



                } 
                else if (PARALLEL_MODE    //for parallel mode       
                        && ftpStopCount <ftpasynclist.size() 
                        && testRunning) {
                    System.out.println("stopCount before condition= " +ftpStopCount);
                    if (ftpStopCount == ftpasynclist.size() -1 && testRunning) {
                        System.out.println("stopCount inside 1st condition= " + ftpStopCount);
                        ftpStopCount = 0;
                        // stopTests(0);
                        startTests();
                        System.out.println("Tests Started");
                    } 
                    else {
                        ftpStopCount++;
                        System.out.println("stopCount after increment = " + ftpStopCount);
                        ;
                    }
                }


            } 
            catch (Exception ed) {
                ed.printStackTrace();
                go.setText(R.string.go);
                //testRunning = false;
            }
            super.onPostExecute(unused);
        }
        private void updateUI(final TextView tv, final String str) {
            runOnUiThread(new Runnable() {
                public void run() {
                    tv.setText(str);
                }
            });
        }

        private void updateUI(final ImageView iv, final int id) {                   // may create problem
            runOnUiThread(new Runnable() {
                public void run() {
                    iv.setImageResource(id);
                }
            });
        }
        public void gotosleep(boolean val) {
            sleep1 = val;
        }

        public boolean areYouSleeping() {
            return sleep1;
        }

    }
4

0 回答 0