onProgressUpdate()在AsyncTask中不起作用

时间:2016-04-05 09:34:30

标签: android android-asynctask

我正在研究一个项目。在这个项目中,我下载了完美的PDF文件,但我想要百分比的进度条。进度条显示,但问题是它不会更新卡在0(零)的进度。我该怎么办?

请参阅我的代码

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    // Progress dialog
    private ProgressDialog mProgressDialog ;
    private int mProgressStatus = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /** Creating a progress dialog window */
        mProgressDialog = new ProgressDialog(this);

        /** Close the dialog window on pressing back button */
        mProgressDialog.setCancelable(true);

        /** Setting a horizontal style progress bar */
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        /** Setting a message for this progress dialog
         * Use the method setTitle(), for setting a title
         * for the dialog window
         *  */
        mProgressDialog.setMessage("Downloading...");


    }

    public void downloadPDF(View v) {

        /** Show the progress dialog window */
        mProgressDialog.show();

        new DownloadFile().execute("https://letuscsolutions.files.wordpress.com/2015/07/five-point-someone-chetan-bhagat_ebook.pdf", "five-point-someone-chetan-bhagat_ebook.pdf");

    }

    public void viewPDF(View v) {
        File pdfFile = new File(Environment.getExternalStorageDirectory() + "/PDF DOWNLOAD/" + "five-point-someone-chetan-bhagat_ebook.pdf");  // -> filename = maven.pdf
        Uri path = Uri.fromFile(pdfFile);
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try {
            startActivity(pdfIntent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
        }
    }

    private class DownloadFile extends AsyncTask<String, Integer, Void> {

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

        @Override
        protected Void doInBackground(String... strings) {

            publishProgress(mProgressStatus);

            String fileUrl = strings[0];   // -> https://letuscsolutions.files.wordpress.com/2015/07/five-point-someone-chetan-bhagat_ebook.pdf
            String fileName = strings[1];  // ->five-point-someone-chetan-bhagat_ebook.pdf
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "PDF DOWNLOAD");
            folder.mkdir();


            File pdfFile = new File(folder, fileName);

            try {
                pdfFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            FileDownloader.downloadFile(fileUrl, pdfFile);
            return null;

        }

        /** This callback method is invoked when publishProgress()
         * method is called */
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            mProgressDialog.setProgress(mProgressStatus);
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            mProgressDialog.dismiss();
            Toast.makeText(getApplicationContext(), "Download PDf successfully", Toast.LENGTH_SHORT).show();
            Log.d("Download complete", "----------");
        }

    }

}

2 个答案:

答案 0 :(得分:1)

您没有计算下载进度。 mProgressStatus将始终为零。 首先以百分比计算下载大小,然后将其存储在mProgressStatus中,然后调用publishProgress(mProgressStatus)

答案 1 :(得分:0)

你应该致电

publishProgress()方法中的

doInBackground(int progress)。

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }