DownLoaderTask.java

[java] view plain copy
  1. packagecom.johnny.testzipanddownload;
  2. importjava.io.BufferedInputStream;
  3. importjava.io.BufferedOutputStream;
  4. importjava.io.File;
  5. importjava.io.FileNotFoundException;
  6. importjava.io.FileOutputStream;
  7. importjava.io.IOException;
  8. importjava.io.InputStream;
  9. importjava.io.OutputStream;
  10. importjava.net.MalformedURLException;
  11. importjava.net.URL;
  12. importjava.net.URLConnection;
  13. importandroid.app.ProgressDialog;
  14. importandroid.content.Context;
  15. importandroid.content.DialogInterface;
  16. importandroid.content.DialogInterface.OnCancelListener;
  17. importandroid.os.AsyncTask;
  18. importandroid.util.Log;
  19. publicclassDownLoaderTaskextendsAsyncTask<Void,Integer,Long>{
  20. privatefinalStringTAG="DownLoaderTask";
  21. privateURLmUrl;
  22. privateFilemFile;
  23. privateProgressDialogmDialog;
  24. privateintmProgress=0;
  25. privateProgressReportingOutputStreammOutputStream;
  26. privateContextmContext;
  27. publicDownLoaderTask(Stringurl,Stringout,Contextcontext){
  28. super();
  29. if(context!=null){
  30. mDialog=newProgressDialog(context);
  31. mContext=context;
  32. }
  33. else{
  34. mDialog=null;
  35. }
  36. try{
  37. mUrl=newURL(url);
  38. StringfileName=newFile(mUrl.getFile()).getName();
  39. mFile=newFile(out,fileName);
  40. Log.d(TAG,"out="+out+",name="+fileName+",mUrl.getFile()="+mUrl.getFile());
  41. }catch(MalformedURLExceptione){
  42. //TODOAuto-generatedcatchblock
  43. e.printStackTrace();
  44. }
  45. }
  46. @Override
  47. protectedvoidonPreExecute(){
  48. //TODOAuto-generatedmethodstub
  49. //super.onPreExecute();
  50. if(mDialog!=null){
  51. mDialog.setTitle("Downloading...");
  52. mDialog.setMessage(mFile.getName());
  53. mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  54. mDialog.setOnCancelListener(newOnCancelListener(){
  55. @Override
  56. publicvoidonCancel(DialogInterfacedialog){
  57. //TODOAuto-generatedmethodstub
  58. cancel(true);
  59. }
  60. });
  61. mDialog.show();
  62. }
  63. }
  64. @Override
  65. protectedLongdoInBackground(Void...params){
  66. //TODOAuto-generatedmethodstub
  67. returndownload();
  68. }
  69. @Override
  70. protectedvoidonProgressUpdate(Integer...values){
  71. //TODOAuto-generatedmethodstub
  72. //super.onProgressUpdate(values);
  73. if(mDialog==null)
  74. return;
  75. if(values.length>1){
  76. intcontentLength=values[1];
  77. if(contentLength==-1){
  78. mDialog.setIndeterminate(true);
  79. }
  80. else{
  81. mDialog.setMax(contentLength);
  82. }
  83. }
  84. else{
  85. mDialog.setProgress(values[0].intValue());
  86. }
  87. }
  88. @Override
  89. protectedvoidonPostExecute(Longresult){
  90. //TODOAuto-generatedmethodstub
  91. //super.onPostExecute(result);
  92. if(mDialog!=null&&mDialog.isShowing()){
  93. mDialog.dismiss();
  94. }
  95. if(isCancelled())
  96. return;
  97. ((MainActivity)mContext).showUnzipDialog();
  98. }
  99. privatelongdownload(){
  100. URLConnectionconnection=null;
  101. intbytesCopied=0;
  102. try{
  103. connection=mUrl.openConnection();
  104. intlength=connection.getContentLength();
  105. if(mFile.exists()&&length==mFile.length()){
  106. Log.d(TAG,"file"+mFile.getName()+"alreadyexits!!");
  107. return0l;
  108. }
  109. mOutputStream=newProgressReportingOutputStream(mFile);
  110. publishProgress(0,length);
  111. bytesCopied=copy(connection.getInputStream(),mOutputStream);
  112. if(bytesCopied!=length&&length!=-1){
  113. Log.e(TAG,"DownloadincompletebytesCopied="+bytesCopied+",length"+length);
  114. }
  115. mOutputStream.close();
  116. }catch(IOExceptione){
  117. //TODOAuto-generatedcatchblock
  118. e.printStackTrace();
  119. }
  120. returnbytesCopied;
  121. }
  122. privateintcopy(InputStreaminput,OutputStreamoutput){
  123. byte[]buffer=newbyte[1024*8];
  124. BufferedInputStreamin=newBufferedInputStream(input,1024*8);
  125. BufferedOutputStreamout=newBufferedOutputStream(output,1024*8);
  126. intcount=0,n=0;
  127. try{
  128. while((n=in.read(buffer,0,1024*8))!=-1){
  129. out.write(buffer,0,n);
  130. count+=n;
  131. }
  132. out.flush();
  133. }catch(IOExceptione){
  134. //TODOAuto-generatedcatchblock
  135. e.printStackTrace();
  136. }finally{
  137. try{
  138. out.close();
  139. }catch(IOExceptione){
  140. //TODOAuto-generatedcatchblock
  141. e.printStackTrace();
  142. }
  143. try{
  144. in.close();
  145. }catch(IOExceptione){
  146. //TODOAuto-generatedcatchblock
  147. e.printStackTrace();
  148. }
  149. }
  150. returncount;
  151. }
  152. privatefinalclassProgressReportingOutputStreamextendsFileOutputStream{
  153. publicProgressReportingOutputStream(Filefile)
  154. throwsFileNotFoundException{
  155. super(file);
  156. //TODOAuto-generatedconstructorstub
  157. }
  158. @Override
  159. publicvoidwrite(byte[]buffer,intbyteOffset,intbyteCount)
  160. throwsIOException{
  161. //TODOAuto-generatedmethodstub
  162. super.write(buffer,byteOffset,byteCount);
  163. mProgress+=byteCount;
  164. publishProgress(mProgress);
  165. }
  166. }
  167. }

解压:

ZipExtractorTask .java

[java] view plain copy
  1. packagecom.johnny.testzipanddownload;
  2. importjava.io.BufferedInputStream;
  3. importjava.io.BufferedOutputStream;
  4. importjava.io.File;
  5. importjava.io.FileNotFoundException;
  6. importjava.io.FileOutputStream;
  7. importjava.io.IOException;
  8. importjava.io.InputStream;
  9. importjava.io.OutputStream;
  10. importjava.util.Enumeration;
  11. importjava.util.zip.ZipEntry;
  12. importjava.util.zip.ZipException;
  13. importjava.util.zip.ZipFile;
  14. importandroid.app.ProgressDialog;
  15. importandroid.content.Context;
  16. importandroid.content.DialogInterface;
  17. importandroid.content.DialogInterface.OnCancelListener;
  18. importandroid.os.AsyncTask;
  19. importandroid.util.Log;
  20. publicclassZipExtractorTaskextendsAsyncTask<Void,Integer,Long>{
  21. privatefinalStringTAG="ZipExtractorTask";
  22. privatefinalFilemInput;
  23. privatefinalFilemOutput;
  24. privatefinalProgressDialogmDialog;
  25. privateintmProgress=0;
  26. privatefinalContextmContext;
  27. privatebooleanmReplaceAll;
  28. publicZipExtractorTask(Stringin,Stringout,Contextcontext,booleanreplaceAll){
  29. super();
  30. mInput=newFile(in);
  31. mOutput=newFile(out);
  32. if(!mOutput.exists()){
  33. if(!mOutput.mkdirs()){
  34. Log.e(TAG,"Failedtomakedirectories:"+mOutput.getAbsolutePath());
  35. }
  36. }
  37. if(context!=null){
  38. mDialog=newProgressDialog(context);
  39. }
  40. else{
  41. mDialog=null;
  42. }
  43. mContext=context;
  44. mReplaceAll=replaceAll;
  45. }
  46. @Override
  47. protectedLongdoInBackground(Void...params){
  48. //TODOAuto-generatedmethodstub
  49. returnunzip();
  50. }
  51. @Override
  52. protectedvoidonPostExecute(Longresult){
  53. //TODOAuto-generatedmethodstub
  54. //super.onPostExecute(result);
  55. if(mDialog!=null&&mDialog.isShowing()){
  56. mDialog.dismiss();
  57. }
  58. if(isCancelled())
  59. return;
  60. }
  61. @Override
  62. protectedvoidonPreExecute(){
  63. //TODOAuto-generatedmethodstub
  64. //super.onPreExecute();
  65. if(mDialog!=null){
  66. mDialog.setTitle("Extracting");
  67. mDialog.setMessage(mInput.getName());
  68. mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  69. mDialog.setOnCancelListener(newOnCancelListener(){
  70. @Override
  71. publicvoidonCancel(DialogInterfacedialog){
  72. //TODOAuto-generatedmethodstub
  73. cancel(true);
  74. }
  75. });
  76. mDialog.show();
  77. }
  78. }
  79. @Override
  80. protectedvoidonProgressUpdate(Integer...values){
  81. //TODOAuto-generatedmethodstub
  82. //super.onProgressUpdate(values);
  83. if(mDialog==null)
  84. return;
  85. if(values.length>1){
  86. intmax=values[1];
  87. mDialog.setMax(max);
  88. }
  89. else
  90. mDialog.setProgress(values[0].intValue());
  91. }
  92. privatelongunzip(){
  93. longextractedSize=0L;
  94. Enumeration<ZipEntry>entries;
  95. ZipFilezip=null;
  96. try{
  97. zip=newZipFile(mInput);
  98. longuncompressedSize=getOriginalSize(zip);
  99. publishProgress(0,(int)uncompressedSize);
  100. entries=(Enumeration<ZipEntry>)zip.entries();
  101. while(entries.hasMoreElements()){
  102. ZipEntryentry=entries.nextElement();
  103. if(entry.isDirectory()){
  104. continue;
  105. }
  106. Filedestination=newFile(mOutput,entry.getName());
  107. if(!destination.getParentFile().exists()){
  108. Log.e(TAG,"make="+destination.getParentFile().getAbsolutePath());
  109. destination.getParentFile().mkdirs();
  110. }
  111. if(destination.exists()&&mContext!=null&&!mReplaceAll){
  112. }
  113. ProgressReportingOutputStreamoutStream=newProgressReportingOutputStream(destination);
  114. extractedSize+=copy(zip.getInputStream(entry),outStream);
  115. outStream.close();
  116. }
  117. }catch(ZipExceptione){
  118. //TODOAuto-generatedcatchblock
  119. e.printStackTrace();
  120. }catch(IOExceptione){
  121. //TODOAuto-generatedcatchblock
  122. e.printStackTrace();
  123. }finally{
  124. try{
  125. zip.close();
  126. }catch(IOExceptione){
  127. //TODOAuto-generatedcatchblock
  128. e.printStackTrace();
  129. }
  130. }
  131. returnextractedSize;
  132. }
  133. privatelonggetOriginalSize(ZipFilefile){
  134. Enumeration<ZipEntry>entries=(Enumeration<ZipEntry>)file.entries();
  135. longoriginalSize=0l;
  136. while(entries.hasMoreElements()){
  137. ZipEntryentry=entries.nextElement();
  138. if(entry.getSize()>=0){
  139. originalSize+=entry.getSize();
  140. }
  141. }
  142. returnoriginalSize;
  143. }
  144. privateintcopy(InputStreaminput,OutputStreamoutput){
  145. byte[]buffer=newbyte[1024*8];
  146. BufferedInputStreamin=newBufferedInputStream(input,1024*8);
  147. BufferedOutputStreamout=newBufferedOutputStream(output,1024*8);
  148. intcount=0,n=0;
  149. try{
  150. while((n=in.read(buffer,0,1024*8))!=-1){
  151. out.write(buffer,0,n);
  152. count+=n;
  153. }
  154. out.flush();
  155. }catch(IOExceptione){
  156. //TODOAuto-generatedcatchblock
  157. e.printStackTrace();
  158. }finally{
  159. try{
  160. out.close();
  161. }catch(IOExceptione){
  162. //TODOAuto-generatedcatchblock
  163. e.printStackTrace();
  164. }
  165. try{
  166. in.close();
  167. }catch(IOExceptione){
  168. //TODOAuto-generatedcatchblock
  169. e.printStackTrace();
  170. }
  171. }
  172. returncount;
  173. }
  174. privatefinalclassProgressReportingOutputStreamextendsFileOutputStream{
  175. publicProgressReportingOutputStream(Filefile)
  176. throwsFileNotFoundException{
  177. super(file);
  178. //TODOAuto-generatedconstructorstub
  179. }
  180. @Override
  181. publicvoidwrite(byte[]buffer,intbyteOffset,intbyteCount)
  182. throwsIOException{
  183. //TODOAuto-generatedmethodstub
  184. super.write(buffer,byteOffset,byteCount);
  185. mProgress+=byteCount;
  186. publishProgress(mProgress);
  187. }
  188. }
  189. }


Main Activity

MainActivity.java

[java] view plain copy
  1. packagecom.johnny.testzipanddownload;
  2. importandroid.os.Bundle;
  3. importandroid.os.Environment;
  4. importandroid.app.Activity;
  5. importandroid.app.AlertDialog;
  6. importandroid.content.DialogInterface;
  7. importandroid.content.DialogInterface.OnClickListener;
  8. importandroid.util.Log;
  9. importandroid.view.Menu;
  10. publicclassMainActivityextendsActivity{
  11. privatefinalStringTAG="MainActivity";
  12. @Override
  13. protectedvoidonCreate(BundlesavedInstanceState){
  14. super.onCreate(savedInstanceState);
  15. setContentView(R.layout.activity_main);
  16. Log.d(TAG,"Environment.getExternalStorageDirectory()="+Environment.getExternalStorageDirectory());
  17. Log.d(TAG,"getCacheDir().getAbsolutePath()="+getCacheDir().getAbsolutePath());
  18. showDownLoadDialog();
  19. //doZipExtractorWork();
  20. //doDownLoadWork();
  21. }
  22. @Override
  23. publicbooleanonCreateOptionsMenu(Menumenu){
  24. //Inflatethemenu;thisaddsitemstotheactionbarifitispresent.
  25. getMenuInflater().inflate(R.menu.main,menu);
  26. returntrue;
  27. }
  28. privatevoidshowDownLoadDialog(){
  29. newAlertDialog.Builder(this).setTitle("确认")
  30. .setMessage("是否下载?")
  31. .setPositiveButton("是",newOnClickListener(){
  32. @Override
  33. publicvoidonClick(DialogInterfacedialog,intwhich){
  34. //TODOAuto-generatedmethodstub
  35. Log.d(TAG,"onClick1="+which);
  36. doDownLoadWork();
  37. }
  38. })
  39. .setNegativeButton("否",newOnClickListener(){
  40. @Override
  41. publicvoidonClick(DialogInterfacedialog,intwhich){
  42. //TODOAuto-generatedmethodstub
  43. Log.d(TAG,"onClick2="+which);
  44. }
  45. })
  46. .show();
  47. }
  48. publicvoidshowUnzipDialog(){
  49. newAlertDialog.Builder(this).setTitle("确认")
  50. .setMessage("是否解压?")
  51. .setPositiveButton("是",newOnClickListener(){
  52. @Override
  53. publicvoidonClick(DialogInterfacedialog,intwhich){
  54. //TODOAuto-generatedmethodstub
  55. Log.d(TAG,"onClick1="+which);
  56. doZipExtractorWork();
  57. }
  58. })
  59. .setNegativeButton("否",newOnClickListener(){
  60. @Override
  61. publicvoidonClick(DialogInterfacedialog,intwhich){
  62. //TODOAuto-generatedmethodstub
  63. Log.d(TAG,"onClick2="+which);
  64. }
  65. })
  66. .show();
  67. }
  68. publicvoiddoZipExtractorWork(){
  69. //ZipExtractorTasktask=newZipExtractorTask("/storage/usb3/system.zip","/storage/emulated/legacy/",this,true);
  70. ZipExtractorTasktask=newZipExtractorTask("/storage/emulated/legacy/testzip.zip","/storage/emulated/legacy/",this,true);
  71. task.execute();
  72. }
  73. privatevoiddoDownLoadWork(){
  74. DownLoaderTasktask=newDownLoaderTask("http://192.168.9.155/johnny/testzip.zip","/storage/emulated/legacy/",this);
  75. //DownLoaderTasktask=newDownLoaderTask("http://192.168.9.155/johnny/test.h264",getCacheDir().getAbsolutePath()+"/",this);
  76. task.execute();
  77. }
  78. }

更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. android binder机制
  2. android 4.0 中出错 java.lang.Unsupport
  3. Android中的度量单位
  4. Android之Dialog
  5. android native c 的so调试
  6. Android(安卓)多媒体扫描过程(Android(安
  7. 【Android(安卓)Native Code开发系列】
  8. android定位得到城市
  9. Android(安卓)之 ActionBar返回按钮
  10. Ubuntu 10.04安装android NDK