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

2019-12-10 19:58:34王冬梅
  • downloadedSize += fds[i].getDownloadSize();   if (!fds[i].isFinished()) {  
  • finished = false;   }  
  • }   handler.sendEmptyMessage(0);  
  • //线程暂停一秒   sleep(1000);  
  • }   } catch (Exception e) {  
  • e.printStackTrace();   }  
  • }   }  
  • }   public class ThreadDownloadDemo extends Activity { 
  • private TextView downloadurl;  private EditText downloadnum; 
  • private Button downloadbutton;  private ProgressBar downloadProgressBar; 
  • private TextView downloadinfo;  private int downloadedSize = 0; 
  • private int fileSize = 0;  private long downloadtime; 
  • @Overridepublic void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState); 
  • setContentView(R.layout.threaddemo);  downloadurl = (TextView) findViewById(R.id.downloadurl); 
  • downloadurl.setText("http://www.easck.com/201105110911/AA5CC27CBE34DEB50A194581D1300881/Special_323149/%E8%8D%B7%E5%A1%98%E6%9C%88%E8%89%B2.mp3");  downloadnum = (EditText) findViewById(R.id.downloadnum); 
  • downloadinfo = (TextView) findViewById(R.id.downloadinfo);  downloadbutton = (Button) findViewById(R.id.downloadbutton); 
  • downloadProgressBar = (ProgressBar) findViewById(R.id.downloadProgressBar);  downloadProgressBar.setVisibility(View.VISIBLE); 
  • downloadProgressBar.setMax(100);  downloadProgressBar.setProgress(0); 
  • downloadbutton.setOnClickListener(new OnClickListener() {  public void onClick(View v) {download(); 
  • downloadtime = SystemClock.currentThreadTimeMillis();  } 
  • }  ); 
  • }  private void download() {// 获取SD卡目录 
  • String dowloadDir = Environment.getExternalStorageDirectory()+ "/threaddemodownload/";  File file = new File(dowloadDir); 
  • //创建下载目录  if (!file.exists()) {file.mkdirs(); 
  • }//读取下载线程数,如果为空,则单线程下载  int downloadTN = Integer.valueOf("".equals(downloadnum.getText().toString()) ? "1" : downloadnum.getText().toString());