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

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

class DownloadFileFromURL extends AsyncTask {

        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;
            }
        }

    }

你可能感兴趣的:(android)