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

相關文章
相關標籤/搜索