使用下载管理器下载文件并根据点击保存文件

时间:2018-02-19 22:53:47

标签: android-studio android-download-manager download-manager

我有我的下载管理器,如果我尝试下载文件,它可以完美运行。但我有一个问题。

我的活动中有4个CardView,我将它设置为onClickListener,所以当我点击一个CardView时,它会下载文件。

以下是调用下载功能的代码

cardviewR1 = findViewById(R.id.card_viewR1);
cardviewR1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pDialogDL = new ProgressDialog(this);
            pDialogDL.setMessage("A message");
            pDialogDL.setIndeterminate(true);
            pDialogDL.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialogDL.setCancelable(true);
            final DownloadTask downloadTask = new DownloadTask(this);
            downloadTask.execute(R1Holder);
            pDialogDL.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    downloadTask.cancel(true);
                }
            });
        }
    });

这是下载功能

private class DownloadTask extends AsyncTask<String, Integer, String> {

        private Context context;
        private PowerManager.WakeLock mWakeLock;

        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.connect();

                // expect HTTP 200 OK, so we don't mistakenly save error report
                // instead of the file
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage();
                }

                // this will be useful to display download percentage
                // might be -1: server did not report the length
                int fileLength = connection.getContentLength();

                // download the file
                input = connection.getInputStream();
                output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.r1)+"_"+NameHolder+".zip");

                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    // allow canceling with back button
                    if (isCancelled()) {
                        input.close();
                        return null;
                    }
                    total += count;
                    // publishing the progress....
                    if (fileLength > 0) // only if total length is known
                        publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }
            } catch (Exception e) {
                return e.toString();
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }

                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);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    getClass().getName());
            mWakeLock.acquire();
            pDialogDL.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // if we get here, length is known, now set indeterminate to false
            pDialogDL.setIndeterminate(false);
            pDialogDL.setMax(100);
            pDialogDL.setProgress(progress[0]);
        }

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

代码在我的应用程序中工作,但问题是,当我尝试添加第二个CardView时,就像这样

cardviewR2 = findViewById(R.id.card_viewR2);
cardviewR2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pDialogDL = new ProgressDialog(this);
            pDialogDL.setMessage("A message");
            pDialogDL.setIndeterminate(true);
            pDialogDL.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialogDL.setCancelable(true);
            final DownloadTask downloadTask = new DownloadTask(this);
            downloadTask.execute(R2Holder);
            pDialogDL.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    downloadTask.cancel(true);
                }
            });
        }
    });

是的,它会下载第二个文件,但它会覆盖第一个文件。我认为问题就在这里

output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.r1)+"_"+NameHolder+".zip");

任何人都可以帮我这个代码吗? 我需要你的帮助,谢谢

1 个答案:

答案 0 :(得分:0)

通过在具有活动的不同文件中单独创建一个新的下载类来修复它,因此AsyncTask将一次又一次地调用 感谢