【发布时间】:2014-12-31 07:15:40
【问题描述】:
我希望我的程序从 Internet 下载许多图像(大约 500 张)并将它们存储在我的外部存储中。目前,当我下载单个图像时,它会显示一个进度条并正确下载图像。但是,当我尝试使用两个图像复制时,它会为正在下载的两个图像提供“下载完成”的 Toast,但是没有显示任何一个图像的进度条,并且只有第一个图像被正确下载。
这是我的 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 循环来创建数百个下载任务并下载我需要的所有图像,然后我会调用 get 方法。然而,为了让它工作,我首先需要知道为什么当我尝试 2 张图片时只有第一个被下载并且为什么没有显示进度条。另外,如果可能的话,如果我能得到关于如何为所有图像更新我的进度条而不是仅为 1 设计的提示。提前致谢。 (注意所有网址都是正确的。)
【问题讨论】:
-
and then I would call the get method。不,永远不要使用 get 方法。它取消了异步性。只需在一个 AsyncTask 的 doInBackground 中使用 for 循环。
标签: java android android-intent android-asynctask download