Android 文件下载工具类:

/***Alipay.comInc.*Copyright(c)2005-2009AllRightsReserved.*/packagecom.alipay.android.appDemo4;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;importjavax.net.ssl.SSLException;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.HttpStatus;importorg.apache.http.client.HttpClient;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.impl.client.DefaultHttpClient;importandroid.annotation.SuppressLint;importandroid.os.Handler;importandroid.os.Looper;importandroid.os.Message;/***文件下载类,支持断电续传**@authorjianmin.jiang**@version$Id:FileDownloader.java,v0.12012-2-14下午8:41:05jianmin.jiang*Exp$*/@SuppressLint("HandlerLeak")publicfinalclassFileDownloader{privateStringfileUrl;privateStringsavePath;privateStringtmpPath;privateFileDownloader.IDownloadProgressprogressOutput;privateFileFetchfetch;privatebooleanshowProgress;publicFileDownloader(){showProgress=false;}publicFileDownloader(booleanshowProgress){this.showProgress=showProgress;}/***@paramfileUrl*文件下载链接地址*/publicfinalvoidsetFileUrl(StringfileUrl){this.fileUrl=fileUrl;}publicfinalvoidsetShowProgress(booleanshowProgress){this.showProgress=showProgress;}protectedfinalbooleanshowProgress(){returnthis.showProgress;}/***@paramsavePath*文件保存地址,使用绝对路径*/publicfinalvoidsetSavePath(StringsavePath){this.savePath=savePath;this.tmpPath=savePath+".tmp";}/***@paramprogressOutput*下载进度输出类*/publicfinalvoidsetProgressOutput(FileDownloader.IDownloadProgressprogressOutput){if(progressOutput!=null){this.progressOutput=progressOutput;}}publicvoidstart(){finalProgressOutputoutput=newProgressOutput(Looper.getMainLooper());newThread(newRunnable(){publicvoidrun(){fetch=newFileFetch(fileUrl,savePath,FileDownloader.this);longfileLen=-1;if(showProgress){fileLen=getFileSize();if(fileLen<=0){output.sendEmptyMessage(0);return;}}else{deleteFile();}if(showProgress){readTempFile();if(fetch.getFileEnd()!=fileLen){deleteFile();fetch.setFileStart(0);fetch.setFileEnd(fileLen);}}newThread(fetch).start();output.isFinished=false;while(!fetch.isStop()){try{Thread.sleep(1500);}catch(InterruptedExceptione){e.printStackTrace();}output.sendEmptyMessage(0);}output.sendEmptyMessage(0);}}).start();}publicvoidstop(){fetch.stop();}privatelonggetFileSize(){longfileLength=-1;try{HttpEntityentity=getHttpEntity(fileUrl,false);fileLength=entity.getContentLength();}catch(Exceptione){//AppErrorException.printException(this.getClass(),//"cannotgetfilelength",e);e.printStackTrace();}returnfileLength;}privatevoiddeleteFile(){Filefile=newFile(savePath);if(file.exists()){file.delete();}file=newFile(tmpPath);if(file.exists()){file.delete();}}protectedvoidwriteTempFile(){FileOutputStreamout=null;ObjectOutputStreamobjOut=null;try{out=newFileOutputStream(this.tmpPath);objOut=newObjectOutputStream(out);objOut.writeLong(fetch.getFileStart());objOut.writeLong(fetch.getFileEnd());objOut.flush();}catch(Exceptione){e.printStackTrace();}finally{try{out.close();}catch(Exceptione){}try{objOut.close();}catch(Exceptione){}}}privatevoidreadTempFile(){FileInputStreamin=null;ObjectInputStreamobjIn=null;try{in=newFileInputStream(this.tmpPath);objIn=newObjectInputStream(in);fetch.setFileStart(objIn.readLong());fetch.setFileEnd(objIn.readLong());}catch(Exceptione){e.printStackTrace();}finally{try{in.close();}catch(Exceptione){}try{objIn.close();}catch(Exceptione){}}}publicstaticHttpEntitygetHttpEntity(StringnetAddress,booleanisZip)throwsException{try{//HttpGet连接对象HttpGethttpGet=newHttpGet(netAddress);//取得HttpClientHttpClienthttpClient=newDefaultHttpClient();if(isZip){httpGet.addHeader("Accept-Encoding","gzip");}//请求HttpClient,获得HttpResponceHttpResponseresponse=httpClient.execute(httpGet);//请求成功intcode=response.getStatusLine().getStatusCode();if(code==HttpStatus.SC_OK){HttpEntityentity=response.getEntity();returnentity;}else{thrownewException("networkexception,ErrorCode:"+code);}}catch(SSLExceptione){e.printStackTrace();}catch(Exceptione){e.printStackTrace();}returnnull;}privateclassProgressOutputextendsHandler{privatebooleanisFinished;@SuppressLint("HandlerLeak")publicProgressOutput(Looperlooper){super(looper);isFinished=false;}@OverridepublicvoidhandleMessage(Messagemsg){if(progressOutput==null){return;}if(progressOutput==null){return;}try{floatprogress=50;if(showProgress){progress=((fetch.getFileStart()*100)/fetch.getFileEnd());}elseif(fetch.isStop()){progress=100;}if(fetch.isStop()){if(progress==100&&!isFinished){progressOutput.downloadSucess();isFinished=true;}elseif(progress>100){deleteFile();progressOutput.downloadFail();}elseif(!isFinished){progressOutput.downloadFail();}}else{progressOutput.downloadProgress(progress);}}catch(Exceptione){progressOutput.downloadFail();}}}publicinterfaceIDownloadProgress{voiddownloadProgress(floatprogress);voiddownloadSucess();voiddownloadFail();}}


更多相关文章

  1. 分析 flutter 打包流程及 aar 产物,并将最终的 aar 集成到现有工
  2. 编译生成可执行文件(Android(安卓)studio中)并在android设备中执行
  3. [转]Android(安卓)开源项目分类汇总
  4. Eclipse+PhoneGap生成Android应用。
  5. 更改Android模拟器中的hosts文件
  6. android背景与style的设置
  7. Android(安卓)Studio学习之对文件的基本了解
  8. Android的adb ||开发事项及Eclipse使用
  9. NPM 和webpack 的基础使用

随机推荐

  1. golang 管道线程安全吗
  2. golang的zap怎么使用
  3. golang 如何模块化
  4. golang调试工具有哪些?
  5. golang的slice如何去重
  6. golang判断map中指定key是否存在
  7. golang指针传递和值传递的区别是什么?
  8. golang的hashmap怎么扩容
  9. golang 如何类型转换
  10. golang有类(class)吗?