Android实现多线程下载文件的方法

2019-12-10 19:58:34王冬梅
  • String fileName = "hetang.mp3";  //开始下载前把下载按钮设置为不可用 
  • downloadbutton.setClickable(false);  //进度条设为0 
  • downloadProgressBar.setProgress(0);  //启动文件下载线程 
  • new downloadTask("http://www.easck.com/201105110911/AA5CC27CBE34DEB50A194581D1300881/Special_323149/%E8%8D%B7%E5%A1%98%E6%9C%88%E8%89%B2.mp3", Integer.valueOf(downloadTN), dowloadDir + fileName).start();  } 
  • Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {  //当收到更新视图消息时,计算已完成下载百分比,同时更新进度条信息 
  • int progress = (Double.valueOf((downloadedSize * 1.0 / fileSize * 100))).intValue();  if (progress == 100) {downloadbutton.setClickable(true); 
  • downloadinfo.setText("下载完成!");  Dialog mdialog = new AlertDialog.Builder(ThreadDownloadDemo.this).setTitle("提示信息").setMessage("下载完成,总用时为:"+(SystemClock.currentThreadTimeMillis()-downloadtime)+"毫秒").setNegativeButton("确定", new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss(); 
  • }}).create();  mdialog.show(); 
  • } else {  downloadinfo.setText("当前进度:" + progress + "%"); 
  • }  downloadProgressBar.setProgress(progress); 
  • }  };  
  • public class downloadTask extends Thread {private int blockSize, downloadSizeMore;  private int threadNum = 5; 
  • String urlStr, threadNo, fileName;  public downloadTask(String urlStr, int threadNum, String fileName) { 
  • this.urlStr = urlStr;  this.threadNum = threadNum; 
  • this.fileName = fileName;  } 
  • @Overridepublic void run() {  FileDownloadThread[] fds = new FileDownloadThread[threadNum]; 
  • try {URL url = new URL(urlStr);  URLConnection conn = url.openConnection(); 
  • //防止返回-1  InputStream in = conn.getInputStream(); 
  • //获取下载文件的总大小  fileSize = conn.getContentLength();