AsyncTask下载文件

来源:互联网 发布:淘宝上的祛湿茶哪个好 编辑:程序博客网 时间:2024/05/16 18:53

AsyncTask下载文件

// 文件保存路径    String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";    public void myClick(View view) {        String downUrl = "http://192.168.1.106/MPC-HC.1.7.10.x86.zip";        new DownloadTask().execute(downUrl);    }    /**     * @params String  下载路径     * @params Integer 下载进度     * @params String 下载结果     */    class DownloadTask extends AsyncTask<String, Integer, String> {        @Override        protected String doInBackground(String... params) {            URL url = null;            InputStream is = null;            FileOutputStream fos = null;            String result = "";            try {                // 创建URL对象                url = new URL(params[0]);                // 打开连接                URLConnection connection = url.openConnection();                // 获取下载文件总长度                int totalLength = connection.getContentLength();                // 获取输入流               is= connection.getInputStream();                int indexOf = params[0].lastIndexOf('/');                // 截获文件名                String filename = params[0].substring(indexOf);                // 获取输出流               fos = new FileOutputStream(savePath + filename);                int len = 0;                int sum = 0;                byte[] bytes = new byte[1024];                while (-1!=(len=is.read(bytes))){                    fos.write(bytes,0,len);                    sum +=len;                    // 推送下载进度                    publishProgress(sum*100/totalLength);                }                result = "下载成功";            } catch (MalformedURLException e) {                result = "下载失败";                e.printStackTrace();            } catch (IOException e) {                result = "下载失败";                e.printStackTrace();            }            return result;        }        /**         * 在此方法中更新下载进度         * @param values         */        @Override        protected void onProgressUpdate(Integer... values) {            super.onProgressUpdate(values);            mTv.setText("当前进度"+values[0]+"%");        }        @Override        protected void onPostExecute(String s) {            super.onPostExecute(s);            mTv.setText(s);        }    }

这里写图片描述

0 0
原创粉丝点击