Android带进度条文件上传
16lz
2021-01-25
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 ?- importjava.io.FilterOutputStream;
- importjava.io.IOException;
- importjava.io.OutputStream;
- importjava.nio.charset.Charset;
- importorg.apache.http.entity.mime.HttpMultipartMode;
- importorg.apache.http.entity.mime.MultipartEntity;
- publicclassCustomMultiPartEntityextendsMultipartEntity
- {
- privatefinalProgressListenerlistener;
- publicCustomMultiPartEntity(finalProgressListenerlistener)
- {
- super();
- this.listener=listener;
- }
- publicCustomMultiPartEntity(finalHttpMultipartModemode,finalProgressListenerlistener)
- {
- super(mode);
- this.listener=listener;
- }
- publicCustomMultiPartEntity(HttpMultipartModemode,finalStringboundary,finalCharsetcharset,finalProgressListenerlistener)
- {
- super(mode,boundary,charset);
- this.listener=listener;
- }
- @Override
- publicvoidwriteTo(finalOutputStreamoutstream)throwsIOException
- {
- super.writeTo(newCountingOutputStream(outstream,this.listener));
- }
- publicstaticinterfaceProgressListener
- {
- voidtransferred(longnum);
- }
- publicstaticclassCountingOutputStreamextendsFilterOutputStream
- {
- privatefinalProgressListenerlistener;
- privatelongtransferred;
- publicCountingOutputStream(finalOutputStreamout,finalProgressListenerlistener)
- {
- super(out);
- this.listener=listener;
- this.transferred=0;
- }
- publicvoidwrite(byte[]b,intoff,intlen)throwsIOException
- {
- out.write(b,off,len);
- this.transferred+=len;
- this.listener.transferred(this.transferred);
- }
- publicvoidwrite(intb)throwsIOException
- {
- out.write(b);
- this.transferred++;
- this.listener.transferred(this.transferred);
- }
- }
- }
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
- classHttpMultipartPostextendsAsyncTask<HttpResponse,Integer,TypeUploadImage>
- {
- ProgressDialogpd;
- longtotalSize;
- @Override
- protectedvoidonPreExecute()
- {
- pd=newProgressDialog(this);
- pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- pd.setMessage("UploadingPicture...");
- pd.setCancelable(false);
- pd.show();
- }
- @Override
- protectedTypeUploadImagedoInBackground(HttpResponse...arg0)
- {
- HttpClienthttpClient=newDefaultHttpClient();
- HttpContexthttpContext=newBasicHttpContext();
- HttpPosthttpPost=newHttpPost("http://herpderp.com/UploadImage.php");
- try
- {
- CustomMultipartEntitymultipartContent=newCustomMultipartEntity(newProgressListener()
- {
- @Override
- publicvoidtransferred(longnum)
- {
- publishProgress((int)((num/(float)totalSize)*100));
- }
- });
- //WeuseFileBodytotransferanimage
- multipartContent.addPart("uploaded_file",newFileBody(newFile(m_userSelectedImagePath)));
- totalSize=multipartContent.getContentLength();
- //Sendit
- httpPost.setEntity(multipartContent);
- HttpResponseresponse=httpClient.execute(httpPost,httpContext);
- StringserverResponse=EntityUtils.toString(response.getEntity());
- ResponseFactoryrp=newResponseFactory(serverResponse);
- return(TypeImage)rp.getData();
- }
- catch(Exceptione)
- {
- System.out.println(e);
- }
- returnnull;
- }
- @Override
- protectedvoidonProgressUpdate(Integer...progress)
- {
- pd.setProgress((int)(progress[0]));
- }
- @Override
- protectedvoidonPostExecute(TypeUploadImageui)
- {
- pd.dismiss();
- }
更多相关文章
- 代码中设置drawableleft
- android 3.0 隐藏 系统标题栏
- Android开发中activity切换动画的实现
- Android(安卓)学习 笔记_05. 文件下载
- Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
- 技术博客汇总
- android 2.3 wifi (一)
- AndRoid Notification的清空和修改
- Android中的Chronometer