0

我正在尝试从 FTP 服务器下载电影。可以成功下载,但是看不到下载进度。你能告诉我为什么 publishProgress() 不能正常工作吗?

以下是我的代码

    public void doClick(View v){
    boolean x  = decodedLink.startsWith("ftp://");     
    boolean y  = decodedLink.startsWith("http://");
    if(x ==true && y==false)
    {
        //ftp

        myurl = null;
        try {
            myurl = new URL("ftp://newrising:newrising2014cap!@newrising.win5.siteonlinetest.com/dummy/giant.mp4");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        pd = new ProgressDialog(this);
        pd.setTitle("EOrder");
        pd.setMessage("Downloading file. Please wait...");
        pd.setIndeterminate(false);
        pd.setMax(100);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setCancelable(true);
        new FTPDownload().execute(myurl);

    }       
    else if(x ==false && y==true)
    {
        //http
    }
    else
    {
        //invalid message
    }
}




class FTPDownload extends AsyncTask<URL , Integer , Void>{

    boolean running = true;
    int count ;
    Date today = Calendar.getInstance().getTime();    
    Format formatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
    String reportDate = formatter.format(today);


    String file = reportDate + "_" + "giant.mp4";

    @Override
    protected Void doInBackground(URL... params) {
        // TODO Auto-generated method stub
        Log.d("******", "Background thread starting......"); 
        try
        {
            URL url = new URL("ftp://newrising:newrising2014cap!@newrising.win5.siteonlinetest.com/dummy/giant.mp4");
            URLConnection conection = url.openConnection();
            conection.connect();
            int lenghtOfFile = conection.getContentLength();        
            Log.d("lenghtOfFile","values: "+lenghtOfFile);
            InputStream input = new BufferedInputStream(url.openStream(), 8192);         
            OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + File.separator + file);       
            byte data[] = new byte[1024];        
            long total = 0;

            while ((count = input.read(data)) != -1) {                      
                total += count;             
                publishProgress((int)((total/lenghtOfFile)*100));                               
                output.write(data, 0, count);

            }        
            output.flush();      
            output.close();
            input.close();
        }
        catch(Exception e)
        {                
            System.out.println("Error: could not connect to host " + decodedLink);
            e.printStackTrace();
        }

        return null;
    }

    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);           
        Log.d("progress","values: "+progress[0]);
        pd.setProgress(progress[0]);
    }


    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        pd.dismiss();
    }

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

    @Override
    protected void onCancelled() {
        running = false;
    }
4

2 回答 2

1

试试这个代码

希望这会奏效..它也会向您显示下载进度。

new DownloadFileAsync().execute(fileURL);

class DownloadFileAsync extends AsyncTask<String, String, String> {

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

        }

        @Override
        protected String doInBackground(String... aurl) {

            try {
                // connecting to url
                URL u = new URL(downloadURL);
                HttpURLConnection c = (HttpURLConnection) u.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();

                // lenghtOfFile is used for calculating download progress
                int lenghtOfFile = c.getContentLength();

                // this is where the file will be seen after the download
                FileOutputStream f = new FileOutputStream(new File(rootDir
                        + "/my_downloads/", fileName));
                // file input is from the url
                InputStream in = c.getInputStream();

                // here's the download code
                byte[] buffer = new byte[1024];
                int len1 = 0;
                long total = 0;

                while ((len1 = in.read(buffer)) > 0) {
                    total += len1; // total = total + len1
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                    f.write(buffer, 0, len1);

                }
                f.close();

            } catch (Exception e) {
                Log.d(LOG_TAG, e.getMessage());

            }

            return null;
        }

        protected void onProgressUpdate(String... progress) {
            // Log.d(LOG_TAG,progress[0]);
            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
            downloadtext.setText(progress[0] + "%");
        }

        @Override
        protected void onPostExecute(String unused) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);

        }
    }


@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS: // we set this to 0
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading file...");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setMax(100);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(true);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }
    }

如果您需要更多帮助,请告诉我

谢谢乌默

于 2013-06-19T06:45:22.047 回答
0

我建议您在 onProgressUpdate 中执行以下操作

@Override
    protected void onProgressUpdate(Integer... progress) {
        int count = (progress[0]+1);
        if(FTPDownload.this.isCancelled())
        {
                   //Handle the canceling of the AsyncTask Exection
        }
else{
            pd.setMessage( count+" Of "+mCount+" Downloaded");
                    pd.show();
        }
于 2013-06-19T06:40:14.483 回答