Android 下载文件并显示进度条

OK,上一篇文章讲了上传文件到服务端,并显示进度条java

那么这边文章主要讲下载文件并显示进度条。ide

因为简单,因此只上传代码.仍是须要用到HttpURLConnection 类,固然你也须要定义一个handle 去接收完成或失败的消息this

首先先定义变量url

private ProgressBar mPgBar;

 private boolean interceptFlag = false;

而后开始编写一个Task 类 去实现下载功能。code

class DownloadTask extends  AsyncTask<Object,Integer,Void>{
        private String savePath;

        private String uri;

        public DownloadTask(String savePath,String uri){
            this.savePath = savePath;

            this.uri = uri;
        }

        @Override
        protected Void doInBackground(Object... objects) {
            String saveFileName ="download."+uri.substring(uri.lastIndexOf(".")-1,uri.length());
            try {
                URL url = new URL(uri);

                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();
                //判断是否挂载了SD卡
                String storageState = Environment.getExternalStorageState();
                if(storageState.equals(Environment.MEDIA_MOUNTED)){
                    File file = new File(savePath);
                    if(!file.exists()){
                        file.mkdirs();
                    }
                    saveFileName = savePath + saveFileName;
                }

                File file = new File(savePath);
                if(!file.exists()){
                    file.mkdirs();
                }
                File mDownloadFile = new File(saveFileName);
                FileOutputStream fos = new FileOutputStream(mDownloadFile);

                int count = 0;
                byte buf[] = new byte[1024];

                do{
                    int numread = is.read(buf);
                    count += numread;
                    publishProgress((int)(((float)count / length) * 100));
                    //更新进度
                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                    if(numread <= 0){
                        //下载完成通知安装
                        mHandler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    fos.write(buf,0,numread);
                }while(!interceptFlag);//点击取消就中止下载.

                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch(IOException e){
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onProgressUpdate(Integer... progress) {
            mPgBar.setProgress(progress[0]);
        }
    }

那么到这里就完成下载的功能了。orm


小伙伴能够尝试下载看看。
get

相关文章
相关标签/搜索