如何使用AsyncTask(Android)下载多个图像并拥有一个进度条

时间:2014-12-31 07:15:41

标签: java android android-intent android-asynctask download

我希望我的程序从互联网上下载许多图像(大约500张)并将它们存储在我的外部存储器中。目前,当我下载单个图像时,它会显示progressBar并正确下载图像。然而,当我试图复制w /两个图像时,它会给出Toast for" Download complete"对于正在下载的两个图像,但是没有显示任何图像的progressBar,只有第一个图像被正确下载。

以下是我的onCreate活动方法的代码。

  

protected void onCreate(Bundle savedInstanceState){           super.onCreate(savedInstanceState);           //删除标题栏           this.requestWindowFeature(Window.FEATURE_NO_TITLE);           //强制纵向方向。 (没有横向)。           setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);           的setContentView(R.layout.activity_quran);

    //Instantiate ProgressDialog (Used for downloading quran pages).
    myProgressDialog = new ProgressDialog(QuranActivity.this);
    myProgressDialog.setMessage("Downloading Quran");
    myProgressDialog.setIndeterminate(true);
    myProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    myProgressDialog.setCancelable(true);

    //execute when the downloader must be fired.
    final DownloadTask downloadTask = new DownloadTask(QuranActivity.this);
    DownloadTask second = new DownloadTask(getApplicationContext());
    myHTTPURL = "https://ia601608.us.archive.org/BookReader/BookReaderImages.php?zip=/10/items/05Quran15LineWhitePageWithVioletBorderWww.Momeen.blogspot.com/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2.zip&file=05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_0001.jp2&scale=1&rotate=0";
    myHTTPURL2 = "https://ia601608.us.archive.org/BookReader/BookReaderImages.php?zip=/10/items/05Quran15LineWhitePageWithVioletBorderWww.Momeen.blogspot.com/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2.zip&file=05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_0002.jp2&scale=1&rotate=0";

    //First check if the file has already been created. (Only need to download 1ce, or
    //in the case where the user deleted the files, we reinstall them again).
    if (isExternalStorageWritable()) {
        File makeDirectory = getQuranStorageDir(QuranActivity.this, "Quran_Pages");

            for (int i = 0; i < 2; i++) {
                Bundle myBundle = new Bundle();
                myBundle.putInt("i", i);
                if (i == 0) {
                    downloadTask.execute(myHTTPURL);

                    try {
                        downloadTask.get();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }

                    myProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            downloadTask.cancel(true);
                        }
                    });


                } else {
                    /*if (downloadTask.getStatus() == AsyncTask.Status.FINISHED) {
                        downloadTask.execute(myHTTPURL2);
                    } else if (downloadTask.getStatus() == AsyncTask.Status.RUNNING) {
                        try {
                            downloadTask.execute(myHTTPURL2).wait(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } */
                    second.execute(myHTTPURL2);
                    try {
                        second.get();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                  //  downloadTask.execute(myHTTPURL2);

                }
            }
    }

这是我的AsynTask类的代码。

  

@TargetApi(Build.VERSION_CODES.FROYO)       私有类DownloadTask扩展AsyncTask {           私有上下文;           私人PowerManager.WakeLock myWakeLock;

    public DownloadTask(Context context) {
        this.context = context;
    }


    @Override
    protected String doInBackground(String... sUrl) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("GET");
            connection.connect();

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }

            //Display download percentage.
            int fileLength = connection.getContentLength();

            //create folder to place the downloaded file in.
            // File Path:E:\Android\data\com.syedabdullah.syed.quran_memorization_application
            //                          \files\Quran Memorization Application\Quran_Pictures
            //So first create a root folder Quran Memorization Application then inside that
            //folder we create another folder named Quran Pictures.

       /*     File rootFolder = new File(getExternalFilesDir("Quran Memorization Application"),
                    "Quran_Pages"); */

            //Here we insert inside the Quran_Pictures folder the quran_pages.
            //String myFileName = "quran_01.jpg";
            Bundle y = new Bundle();
            int retrievePos = y.getInt("i");
            String quranFilePageName = "_" + retrievePos + ".jpg";
          //  String fileName = "justwork.jpg";
            File sup = new File(getExternalFilesDir("Quran Memorization Application"), "Quran_Pages");
            File myFile = new File(sup, quranFilePageName);
            myFile.createNewFile();

            //downlaod the file.
            input = connection.getInputStream();
            output = new FileOutputStream(myFile);

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                //allow cancel with back button.
                if (isCancelled()) {
                    input.close();
                    return null;
                }
                total += count;
                //publish the progress.
                if (fileLength > 0) {
                    publishProgress((int) (total * 100 / fileLength));
                }
                output.write(data, 0, count);
            }
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            intent.setData(Uri.fromFile(myFile));
            QuranActivity.this.sendBroadcast(intent);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) {
                    output.close();
                }
                if (input != null) {
                    input.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //Take CPU lock to prevent CPU from going off if the user presses the power button.
        //during download.
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        myWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
        myWakeLock.acquire();
        myProgressDialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        //If we get here length is known, so setIndertimante to false.
        myProgressDialog.setIndeterminate(false);
        myProgressDialog.setMax(100);
        myProgressDialog.setProgress(progress[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        myWakeLock.release();
        myProgressDialog.dismiss();
        if (result != null) {
            Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(context, "Download Complete", Toast.LENGTH_SHORT).show();
        }

    }
} }

我希望有一个for循环可以创建数百个downloadTasks并下载我需要的所有图像,然后我会调用get方法。然而,为了使其工作,我首先需要知道为什么当我尝试2个图像时,只有第一个被下载,为什么没有进度条出现。如果可能的话,如果我可以得到一个提示,我可以如何为所有图像进行progressBar更新而不是仅为1设计。提前感谢。 (注意所有URL都是当前的。)

1 个答案:

答案 0 :(得分:0)

非常感谢你!我发现我的循环被认为是进入doInBackground。还有其他有类似问题的人。要下载多个文件并显示一个不错的progressBar,这是一个非常棒的教程:http://theopentutorials.com/tutorials/android/dialog/android-download-multiple-files-showing-progress-bar/