Android安卓根据地址下载文件并保存到本地(HttpDownload)

本文介绍如何在Android应用中使用AsyncTask下载文件,同时实现进度条的实时更新。通过这种方法,确保文件下载完整且不失真,涵盖了下载状态的判断与处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  安卓根据地址下载文件并保存到本地,这里主要是用asyncTask中实现,并实现进度条实时更新。根据下载结果,判断返回3中情况:已下载,失败,成功。此方法下载保证可以保证下载不失真,不会出现下载大小与实际不符的情况,此处只列出AsyncTask的代码,供参考。如有问题,请在评论中指出。

class DownloadFileFromURL extends AsyncTask<String, String, Integer> {

        File file = null;
        String filePath;

        /**
         * Before starting background thread Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //显示进度条
            mProgress.setVisibility(View.VISIBLE);
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected Integer doInBackground(String... f_url) {
            int count;
            int result = 0;

            int lenghtOfFile = 0;
            long total = 0;

            String SDPATH = Environment.getExternalStorageDirectory() + "/";
            String fileName = "Download/test.pdf";//文件名

            File dir = new File(SDPATH + "Download/");//路径
            if (!dir.exists()) {
                dir.mkdir();
            }

            filePath = SDPATH + fileName;
            file = new File(SDPATH + fileName);
            if (!file.exists()) {

                try {
                    URL url = new URL(f_url[0]);
                    URLConnection conection = url.openConnection();
                    conection.connect();
                    // this will be useful so that you can show a tipical 0-100%
                    // progress bar
                    lenghtOfFile = conection.getContentLength();

                    // download the file
                    InputStream input = new BufferedInputStream(
                            url.openStream(), 8192);

                    file.createNewFile();

                    // Output stream
                    OutputStream output = new FileOutputStream(file);

                    byte data[] = new byte[1024];

                    while ((count = input.read(data)) != -1) {
                        total += count;

                        publishProgress(""
                                + (int) ((total * 100) / lenghtOfFile));

                        // writing data to file
                        output.write(data, 0, count);
                    }

                    // flushing output
                    output.flush();

                    // closing streams
                    output.close();
                    input.close();

                } catch (Exception e) {
                    Log.e("Error: ", e.getMessage());
                }

                if (lenghtOfFile == 0 || total < lenghtOfFile) {
                    result = -1;
                } else {
                    result = 1;
                }

            }
            return result;
        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            // pDialog.setProgress(Integer.parseInt(progress[0]));
            mProgressValue.setText(Integer.parseInt(progress[0]) + "%");
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(Integer result) {
            // dismiss the dialog after the file was downloaded

            mProgress.setVisibility(View.GONE);
            switch (result) {
            case 0:
            //已经下载
                break;
            case -1:
            //下载失败
                break;
            case 1:
            //下载成功
                break;

            default:
                break;
            }
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值