Being able to display a progress bar during a time consuming upload to a web server is important when dealing with users and appeasing their impatience. Here is one approach of achieving this.

In this example we are going to use 2 classes – the first one is going to implement Android’s really handy threading function: Async Task and the other is going to extend MutlipartEntity – the basic object used for a multipart POST. Let’s take a look at extending a MultipartEntity object:

CustomMultiPartEntity.java

[java] view plain copy print ?
  1. importjava.io.FilterOutputStream;
  2. importjava.io.IOException;
  3. importjava.io.OutputStream;
  4. importjava.nio.charset.Charset;
  5. importorg.apache.http.entity.mime.HttpMultipartMode;
  6. importorg.apache.http.entity.mime.MultipartEntity;
  7. publicclassCustomMultiPartEntityextendsMultipartEntity
  8. {
  9. privatefinalProgressListenerlistener;
  10. publicCustomMultiPartEntity(finalProgressListenerlistener)
  11. {
  12. super();
  13. this.listener=listener;
  14. }
  15. publicCustomMultiPartEntity(finalHttpMultipartModemode,finalProgressListenerlistener)
  16. {
  17. super(mode);
  18. this.listener=listener;
  19. }
  20. publicCustomMultiPartEntity(HttpMultipartModemode,finalStringboundary,finalCharsetcharset,finalProgressListenerlistener)
  21. {
  22. super(mode,boundary,charset);
  23. this.listener=listener;
  24. }
  25. @Override
  26. publicvoidwriteTo(finalOutputStreamoutstream)throwsIOException
  27. {
  28. super.writeTo(newCountingOutputStream(outstream,this.listener));
  29. }
  30. publicstaticinterfaceProgressListener
  31. {
  32. voidtransferred(longnum);
  33. }
  34. publicstaticclassCountingOutputStreamextendsFilterOutputStream
  35. {
  36. privatefinalProgressListenerlistener;
  37. privatelongtransferred;
  38. publicCountingOutputStream(finalOutputStreamout,finalProgressListenerlistener)
  39. {
  40. super(out);
  41. this.listener=listener;
  42. this.transferred=0;
  43. }
  44. publicvoidwrite(byte[]b,intoff,intlen)throwsIOException
  45. {
  46. out.write(b,off,len);
  47. this.transferred+=len;
  48. this.listener.transferred(this.transferred);
  49. }
  50. publicvoidwrite(intb)throwsIOException
  51. {
  52. out.write(b);
  53. this.transferred++;
  54. this.listener.transferred(this.transferred);
  55. }
  56. }
  57. }
import java.io.FilterOutputStream;import java.io.IOException;import java.io.OutputStream;import java.nio.charset.Charset;import org.apache.http.entity.mime.HttpMultipartMode;import org.apache.http.entity.mime.MultipartEntity; public class CustomMultiPartEntity extends MultipartEntity{ private final ProgressListener listener; public CustomMultiPartEntity(final ProgressListener listener){super();this.listener = listener;} public CustomMultiPartEntity(final HttpMultipartMode mode, final ProgressListener listener){super(mode);this.listener = listener;} public CustomMultiPartEntity(HttpMultipartMode mode, final String boundary, final Charset charset, final ProgressListener listener){super(mode, boundary, charset);this.listener = listener;} @Overridepublic void writeTo(final OutputStream outstream) throws IOException{super.writeTo(new CountingOutputStream(outstream, this.listener));} public static interface ProgressListener{void transferred(long num);} public static class CountingOutputStream extends FilterOutputStream{ private final ProgressListener listener;private long transferred; public CountingOutputStream(final OutputStream out, final ProgressListener listener){super(out);this.listener = listener;this.transferred = 0;} public void write(byte[] b, int off, int len) throws IOException{out.write(b, off, len);this.transferred += len;this.listener.transferred(this.transferred);} public void write(int b) throws IOException{out.write(b);this.transferred++;this.listener.transferred(this.transferred);}}}


By simply counting the amount of bytes that are written, we can implement an interface (here we called it trasnfered())which can be called in our main class to update our progress bar dialog box:

Main.java

[java] view plain copy print ?
  1. classHttpMultipartPostextendsAsyncTask<HttpResponse,Integer,TypeUploadImage>
  2. {
  3. ProgressDialogpd;
  4. longtotalSize;
  5. @Override
  6. protectedvoidonPreExecute()
  7. {
  8. pd=newProgressDialog(this);
  9. pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  10. pd.setMessage("UploadingPicture...");
  11. pd.setCancelable(false);
  12. pd.show();
  13. }
  14. @Override
  15. protectedTypeUploadImagedoInBackground(HttpResponse...arg0)
  16. {
  17. HttpClienthttpClient=newDefaultHttpClient();
  18. HttpContexthttpContext=newBasicHttpContext();
  19. HttpPosthttpPost=newHttpPost("http://herpderp.com/UploadImage.php");
  20. try
  21. {
  22. CustomMultipartEntitymultipartContent=newCustomMultipartEntity(newProgressListener()
  23. {
  24. @Override
  25. publicvoidtransferred(longnum)
  26. {
  27. publishProgress((int)((num/(float)totalSize)*100));
  28. }
  29. });
  30. //WeuseFileBodytotransferanimage
  31. multipartContent.addPart("uploaded_file",newFileBody(newFile(m_userSelectedImagePath)));
  32. totalSize=multipartContent.getContentLength();
  33. //Sendit
  34. httpPost.setEntity(multipartContent);
  35. HttpResponseresponse=httpClient.execute(httpPost,httpContext);
  36. StringserverResponse=EntityUtils.toString(response.getEntity());
  37. ResponseFactoryrp=newResponseFactory(serverResponse);
  38. return(TypeImage)rp.getData();
  39. }
  40. catch(Exceptione)
  41. {
  42. System.out.println(e);
  43. }
  44. returnnull;
  45. }
  46. @Override
  47. protectedvoidonProgressUpdate(Integer...progress)
  48. {
  49. pd.setProgress((int)(progress[0]));
  50. }
  51. @Override
  52. protectedvoidonPostExecute(TypeUploadImageui)
  53. {
  54. pd.dismiss();
  55. }

更多相关文章

  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. MTK 平台(MTK6573)马达驱动
  2. 跑马灯
  3. Android10共享文件总是读取不到文件,文件
  4. Android(安卓)ListView移动至指定行
  5. android 输入系统
  6. Android(安卓)shape使用
  7. 《第一行代码——Android》
  8. Android(安卓)开发环境安装 新版本Androi
  9. android 的权限
  10. Android获取其他包的Context实例