//定义下载文件的线程工具类
public class downloadThread extends Thread {
private String sturl;
private String filename;
private int filesize;
private String savepath;
private URL url;
private Handler mhander;
public downloadThread(String sturl,String filename,int filesize,String savepath,Handler handler){
this.sturl=sturl;
this.filename=filename;
this.filesize = filesize;
this.savepath= savepath;
this.mhander=handler;
}
@Override
public void run(){
try{
url= new URL(sturl);
File file = new File(savepath+filename);
if(file.exists()){
file.mkdir();
}
HttpURLConnection urlcom1 = (HttpURLConnection)url.openConnection();
InputStream input = urlcom1.getInputStream();
byte[] bs = new byte[1024];
OutputStream out = new FileOutputStream(file);
int len;
int sizeflag=0;
int flag=0;
while((len= input.read(bs))!=-1){
out.write(bs,0,len);
sizeflag=sizeflag+len;
if(sizeflag*100/filesize-flag>1){
flag=sizeflag*100/filesize;
Message msg = Message.obtain();
msg.what=flag;
mhander.sendMessage(msg);
}
}
input.close();
out.close();
}catch ( MalformedURLException e){
e.printStackTrace();
}
catch (IOException e){
}
}
}
//线程通信handler
Handler downloadhaner = new Handler(){ @Override public void handleMessage(Message msg){ es_dl_tv.setText(msg.what+"%"); es_dl_pb.setProgress(msg.what); } };
//定义的参数
String sturl_dl= ""; String filename_dl = ""; int filesize_dl =0; String savepath_dl =""; String filetype_dl ="";
//初始化下载线程,
downloadThread thread1 = new downloadThread(sturl_dl,filename_dl,filesize_dl,savepath_dl,downloadhaner );
thread1.start();