DBMNG数据库管理与应用

独立思考能力,对于从事科学研究或其他任何工作,都是十分必要的。
当前位置:首页 > 移动应用 > Android

Android OkHttp文件上传与下载的进度监听扩展

来自csdn 安卓弟http://blog.csdn.net/sbsujjbcy,另外okhttp的sample中有代码原型这里    ,可以对照此文相互参考。

相信大家对OkHttp也是相当的熟悉了,毕竟是Square的东西,对于其种种优点,这里也不再叙说。优秀是优秀,但是毕竟优秀的东西给我们封装了太多,那么问题来了,我们使用OkHttp作为我们的网络层,简单地进行GET/POST请求是毫无问题。近日看了产品的设计稿,毛估估会有文件的上传与下载的需求,如果使用OkHttp作为网络层进行封装,你会惊讶的发现,简直封装的太“完美”了。如果现在有这么一个需求,要求对文件进行上传或下载,但是在上传或者下载前,你需要给用户一个友好的提示,在上传或者下载中,你需要将进度展示给用户,下载或者完成后提示用户下载完成。

但是呢,找啊找,你会发现基本上找不到OkHttp的这种用法,百度是找不到,但是你别忘记了还有谷歌,谷歌一搜,Stackoverflow就全出来了,甚至github上的issue都出来了,可见并不是我们遇到了这么一个问题,还要许许多多的人遇到了这个问题,粗粗看了几个回答,感觉有几个还是比较靠谱的。为了日后的重用,我将其封装为一个OkHttp的扩展库,暂时取名为CoreProgress。

要实现进度的监听,需要使用到OkHttp的依赖包Okio里的两个类,一个是Source,一个是Sink,至于Okio的东西,这里也不多说。


首先我们实现文件下载的进度监听。OkHttp给我们的只是一个回调,里面有Response返回结果,我们需要继承一个类,对结果进行监听,这个类就是ResponseBody,但是如何将它设置到OkHttp中去呢,答案是拦截器。拦截器的部分后面再叙述,这里先实现ResponseBody的子类ProgressResponseBody。

要监听进度,我们必然需要一个监听器,也就是一个接口,在其实现类中完成回调内容的处理,该接口声明如下。

  1. /**
  2.  * 响应体进度回调接口,比如用于文件下载中
  3.  * User:lizhangqu(513163535@qq.com)
  4.  * Date:2015-09-02
  5.  * Time: 17:16
  6.  */
  7. public interface ProgressResponseListener {
  8.     void onResponseProgress(long bytesRead, long contentLength, boolean done);
  9. }

然后会使用到该接口

  1. /**
  2.  * 包装的响体,处理进度
  3.  * User:lizhangqu(513163535@qq.com)
  4.  * Date:2015-09-02
  5.  * Time: 17:18
  6.  */
  7. public class ProgressResponseBody extends ResponseBody {
  8.     //实际的待包装响应体
  9.     private final ResponseBody responseBody;
  10.     //进度回调接口
  11.     private final ProgressResponseListener progressListener;
  12.     //包装完成的BufferedSource
  13.     private BufferedSource bufferedSource;
  14.  
  15.     /**
  16.      * 构造函数,赋值
  17.      * @param responseBody 待包装的响应体
  18.      * @param progressListener 回调接口
  19.      */
  20.     public ProgressResponseBody(ResponseBody responseBody, ProgressResponseListener progressListener) {
  21.         this.responseBody = responseBody;
  22.         this.progressListener = progressListener;
  23.     }
  24.  
  25.  
  26.     /**
  27.      * 重写调用实际的响应体的contentType
  28.      * @return MediaType
  29.      */
  30.     @Override public MediaType contentType() {
  31.         return responseBody.contentType();
  32.     }
  33.  
  34.     /**
  35.      * 重写调用实际的响应体的contentLength
  36.      * @return contentLength
  37.      * @throws IOException 异常
  38.      */
  39.     @Override public long contentLength() throws IOException {
  40.         return responseBody.contentLength();
  41.     }
  42.  
  43.     /**
  44.      * 重写进行包装source
  45.      * @return BufferedSource
  46.      * @throws IOException 异常
  47.      */
  48.     @Override public BufferedSource source() throws IOException {
  49.         if (bufferedSource == null) {
  50.             //包装
  51.             bufferedSource = Okio.buffer(source(responseBody.source()));
  52.         }
  53.         return bufferedSource;
  54.     }
  55.  
  56.     /**
  57.      * 读取,回调进度接口
  58.      * @param source Source
  59.      * @return Source
  60.      */
  61.     private Source source(Source source) {
  62.  
  63.         return new ForwardingSource(source) {
  64.             //当前读取字节数
  65.             long totalBytesRead = 0L;
  66.             @Override public long read(Buffer sink, long byteCount) throws IOException {
  67.                 long bytesRead = super.read(sink, byteCount);
  68.                 //增加当前读取的字节数,如果读取完成了bytesRead会返回-1
  69.                 totalBytesRead += bytesRead != -1 ? bytesRead : 0;
  70.                 //回调,如果contentLength()不知道长度,会返回-1
  71.                 progressListener.onResponseProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
  72.                 return bytesRead;
  73.             }
  74.         };
  75.     }
  76. }

类似装饰器,我们对原始的ResponseBody 进行了一层包装。并在其读取数据的时候设置了回调,回调的接口由构造函数传入,此外构造函数还传入了原始的ResponseBody,当系统内部调用了ResponseBody 的source方法的时候,返回的便是我们包装后的Source。然后我们还重写了几个方法调用原始的ResponseBody对应的函数返回结果。

同理既然下载是这样,那么上传也应该是这样,我们乘热打铁完成上传的部分,下载是继承ResponseBody ,上传就是继承RequestBody,同时也应该还有一个监听器。

  1. /**
  2.  * 请求体进度回调接口,比如用于文件上传中
  3.  * User:lizhangqu(513163535@qq.com)
  4.  * Date:2015-09-02
  5.  * Time: 17:16
  6.  */
  7. public interface ProgressRequestListener {
  8.     void onRequestProgress(long bytesWritten, long contentLength, boolean done);
  9. }

RequestBody的子类实现类比ResponseBody ,基本上复制一下稍加修改即可使用。

  1. /**
  2.  * 包装的请求体,处理进度
  3.  * User:lizhangqu(513163535@qq.com)
  4.  * Date:2015-09-02
  5.  * Time: 17:15
  6.  */
  7. public  class ProgressRequestBody extends RequestBody {
  8.     //实际的待包装请求体
  9.     private final RequestBody requestBody;
  10.     //进度回调接口
  11.     private final ProgressRequestListener progressListener;
  12.     //包装完成的BufferedSink
  13.     private BufferedSink bufferedSink;
  14.  
  15.     /**
  16.      * 构造函数,赋值
  17.      * @param requestBody 待包装的请求体
  18.      * @param progressListener 回调接口
  19.      */
  20.     public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) {
  21.         this.requestBody = requestBody;
  22.         this.progressListener = progressListener;
  23.     }
  24.  
  25.     /**
  26.      * 重写调用实际的响应体的contentType
  27.      * @return MediaType
  28.      */
  29.     @Override
  30.     public MediaType contentType() {
  31.         return requestBody.contentType();
  32.     }
  33.  
  34.     /**
  35.      * 重写调用实际的响应体的contentLength
  36.      * @return contentLength
  37.      * @throws IOException 异常
  38.      */
  39.     @Override
  40.     public long contentLength() throws IOException {
  41.         return requestBody.contentLength();
  42.     }
  43.  
  44.     /**
  45.      * 重写进行写入
  46.      * @param sink BufferedSink
  47.      * @throws IOException 异常
  48.      */
  49.     @Override
  50.     public void writeTo(BufferedSink sink) throws IOException {
  51.         if (bufferedSink == null) {
  52.             //包装
  53.             bufferedSink = Okio.buffer(sink(sink));
  54.         }
  55.         //写入
  56.         requestBody.writeTo(bufferedSink);
  57.         //必须调用flush,否则最后一部分数据可能不会被写入
  58.         bufferedSink.flush();
  59.  
  60.     }
  61.  
  62.     /**
  63.      * 写入,回调进度接口
  64.      * @param sink Sink
  65.      * @return Sink
  66.      */
  67.     private Sink sink(Sink sink) {
  68.         return new ForwardingSink(sink) {
  69.             //当前写入字节数
  70.             long bytesWritten = 0L;
  71.             //总字节长度,避免多次调用contentLength()方法
  72.             long contentLength = 0L;
  73.  
  74.             @Override
  75.             public void write(Buffer source, long byteCount) throws IOException {
  76.                 super.write(source, byteCount);
  77.                 if (contentLength == 0) {
  78.                     //获得contentLength的值,后续不再调用
  79.                     contentLength = contentLength();
  80.                 }
  81.                 //增加当前写入的字节数
  82.                 bytesWritten += byteCount;
  83.                 //回调
  84.                 progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength);
  85.             }
  86.         };
  87.     }
  88. }

内部维护了一个原始的RequestBody 以及一个监听器,同样的也是由构造函数传入。当然也是要重写几个函数调用原始的RequestBody 对应的函数,文件的下载是read函数中进行监听的设置,毫无疑问文件的上传就是write函数了,我们在write函数中进行了类似的操作,并回调了接口中的函数。当系统内部调用了RequestBody 的writeTo函数时,我们对BufferedSink 进行了一层包装,即设置了进度监听,并返回了我们包装的BufferedSink 。于是乎,上传于下载的进度监听就完成了。

还有一个重要的问题就是

如何进行使用呢?

如何进行使用呢?

如何进行使用呢?

重要的事要说三遍。

我们还需要一个Helper类,对上传或者下载进行监听设置。文件的上传其实很简单,将我们的原始RequestBody和监听器 传入,返回我们的包装的ProgressRequestBody ,使用包装后的ProgressRequestBody 进行请求即可,但是文件的下载呢,OkHttp给我们返回的是Response,我们如何将我们包装的ProgressResponseBody设置进去呢,答案之前已经说过了,就是拦截器,具体见代码吧。

  1. /**
  2.  * 进度回调辅助类
  3.  * User:lizhangqu(513163535@qq.com)
  4.  * Date:2015-09-02
  5.  * Time: 17:33
  6.  */
  7. public class ProgressHelper {
  8.     /**
  9.      * 包装OkHttpClient,用于下载文件的回调
  10.      * @param client 待包装的OkHttpClient
  11.      * @param progressListener 进度回调接口
  12.      * @return 包装后的OkHttpClient,使用clone方法返回
  13.      */
  14.     public static OkHttpClient addProgressResponseListener(OkHttpClient client,final ProgressResponseListener progressListener){
  15.         //克隆
  16.         OkHttpClient clone = client.clone();
  17.         //增加拦截器
  18.         clone.networkInterceptors().add(new Interceptor() {
  19.             @Override
  20.             public Response intercept(Chain chain) throws IOException {
  21.                 //拦截
  22.                 Response originalResponse = chain.proceed(chain.request());
  23.                 //包装响应体并返回
  24.                 return originalResponse.newBuilder()
  25.                         .body(new ProgressResponseBody(originalResponse.body(), progressListener))
  26.                         .build();
  27.             }
  28.         });
  29.         return clone;
  30.     }
  31.  
  32.     /**
  33.      * 包装请求体用于上传文件的回调
  34.      * @param requestBody 请求体RequestBody
  35.      * @param progressRequestListener 进度回调接口
  36.      * @return 包装后的进度回调请求体
  37.      */
  38.     public static ProgressRequestBody addProgressRequestListener(RequestBody requestBody,ProgressRequestListener progressRequestListener){
  39.         //包装请求体
  40.         return new ProgressRequestBody(requestBody,progressRequestListener);
  41.     }
  42. }

对于文件下载的监听器我们为了不影响原来的OkHttpClient 实例,我们调用clone方法进行了克隆,之后对克隆的方法设置了响应拦截,并返回该克隆的实例。而文件的上传则十分简单,直接包装后返回即可。

但是你别忘记了,我们的目的是在UI层进行回调,而OkHttp的所有请求都不在UI层。于是我们还要实现我们写的接口,进行UI操作的回调。由于涉及到消息机制,我们对之前的两个接口回调传的参数进行封装,封装为一个实体类便于传递。

  1. /**
  2.  * UI进度回调实体类
  3.  * User:lizhangqu(513163535@qq.com)
  4.  * Date:2015-09-02
  5.  * Time: 22:39
  6.  */
  7. public class ProgressModel implements Serializable {
  8.     //当前读取字节长度
  9.     private long currentBytes;
  10.     //总字节长度
  11.     private long contentLength;
  12.     //是否读取完成
  13.     private boolean done;
  14.  
  15.     public ProgressModel(long currentBytes, long contentLength, boolean done) {
  16.         this.currentBytes = currentBytes;
  17.         this.contentLength = contentLength;
  18.         this.done = done;
  19.     }
  20.  
  21.     public long getCurrentBytes() {
  22.         return currentBytes;
  23.     }
  24.  
  25.     public void setCurrentBytes(long currentBytes) {
  26.         this.currentBytes = currentBytes;
  27.     }
  28.  
  29.     public long getContentLength() {
  30.         return contentLength;
  31.     }
  32.  
  33.     public void setContentLength(long contentLength) {
  34.         this.contentLength = contentLength;
  35.     }
  36.  
  37.     public boolean isDone() {
  38.         return done;
  39.     }
  40.  
  41.     public void setDone(boolean done) {
  42.         this.done = done;
  43.     }
  44.  
  45.     @Override
  46.     public String toString() {
  47.         return "ProgressModel{" +
  48.                 "currentBytes=" + currentBytes +
  49.                 ", contentLength=" + contentLength +
  50.                 ", done=" + done +
  51.                 '}';
  52.     }
  53. }

再实现我们的UI回调接口,对于文件的上传,我们需要实现的是ProgressRequestListener接口,文件的下载需要实现的是ProgressResponseListener接口,但是内部的逻辑处理是完全一样的。我们使用抽象类,提供一个抽象方法,该抽象方法用于UI层回调的处理,由具体开发去实现。涉及到消息机制就涉及到Handler类,在Handler的子类中维护一个弱引用指向外部类(用到了static防止内存泄露,但是需要调用外部类的一个非静态函数,所以将外部类引用直接由构造函数传入,在内部通过调用该引用的方法去实现),然后将主线程的Looper传入,调用父类构造函数。在onRequestProgress中发送进度更新的消息,在handleMessage函数中回调我们的抽象方法。我们只需要实现抽象方法,编写对应的UI更新代码即可。具体代码如下。

  1. /**
  2.  * 请求体回调实现类,用于UI层回调
  3.  * User:lizhangqu(513163535@qq.com)
  4.  * Date:2015-09-02
  5.  * Time: 22:34
  6.  */
  7. public abstract class UIProgressRequestListener implements ProgressRequestListener {
  8.     private static final int REQUEST_UPDATE = 0x01;
  9.  
  10.     //处理UI层的Handler子类
  11.     private static class UIHandler extends Handler {
  12.         //弱引用
  13.         private final WeakReference<UIProgressRequestListener> mUIProgressRequestListenerWeakReference;
  14.  
  15.         public UIHandler(Looper looper, UIProgressRequestListener uiProgressRequestListener) {
  16.             super(looper);
  17.             mUIProgressRequestListenerWeakReference = new WeakReference<UIProgressRequestListener>(uiProgressRequestListener);
  18.         }
  19.  
  20.         @Override
  21.         public void handleMessage(Message msg) {
  22.             switch (msg.what) {
  23.                 case REQUEST_UPDATE:
  24.                     UIProgressRequestListener uiProgressRequestListener = mUIProgressRequestListenerWeakReference.get();
  25.                     if (uiProgressRequestListener != null) {
  26.                         //获得进度实体类
  27.                         ProgressModel progressModel = (ProgressModel) msg.obj;
  28.                         //回调抽象方法
  29.                         uiProgressRequestListener.onUIRequestProgress(progressModel.getCurrentBytes(), progressModel.getContentLength(), progressModel.isDone());
  30.                     }
  31.                     break;
  32.                 default:
  33.                     super.handleMessage(msg);
  34.                     break;
  35.             }
  36.         }
  37.     }
  38.     //主线程Handler
  39.     private final Handler mHandler = new UIHandler(Looper.getMainLooper(), this);
  40.  
  41.     @Override
  42.     public void onRequestProgress(long bytesRead, long contentLength, boolean done) {
  43.         //通过Handler发送进度消息
  44.         Message message = Message.obtain();
  45.         message.obj = new ProgressModel(bytesRead, contentLength, done);
  46.         message.what = REQUEST_UPDATE;
  47.         mHandler.sendMessage(message);
  48.     }
  49.  
  50.     /**
  51.      * UI层回调抽象方法
  52.      * @param bytesWrite 当前写入的字节长度
  53.      * @param contentLength 总字节长度
  54.      * @param done 是否写入完成
  55.      */
  56.     public abstract void onUIRequestProgress(long bytesWrite, long contentLength, boolean done);
  57. }

另一个实现类代码雷同,不做叙述。

  1. /**
  2.  * 请求体回调实现类,用于UI层回调
  3.  * User:lizhangqu(513163535@qq.com)
  4.  * Date:2015-09-02
  5.  * Time: 22:34
  6.  */
  7. public abstract class UIProgressResponseListener implements ProgressResponseListener {
  8.     private static final int RESPONSE_UPDATE = 0x02;
  9.     //处理UI层的Handler子类
  10.     private static class UIHandler extends Handler {
  11.         //弱引用
  12.         private final WeakReference<UIProgressResponseListener> mUIProgressResponseListenerWeakReference;
  13.  
  14.         public UIHandler(Looper looper, UIProgressResponseListener uiProgressResponseListener) {
  15.             super(looper);
  16.             mUIProgressResponseListenerWeakReference = new WeakReference<UIProgressResponseListener>(uiProgressResponseListener);
  17.         }
  18.  
  19.         @Override
  20.         public void handleMessage(Message msg) {
  21.             switch (msg.what) {
  22.                 case RESPONSE_UPDATE:
  23.                     UIProgressResponseListener uiProgressResponseListener = mUIProgressResponseListenerWeakReference.get();
  24.                     if (uiProgressResponseListener != null) {
  25.                         //获得进度实体类
  26.                         ProgressModel progressModel = (ProgressModel) msg.obj;
  27.                         //回调抽象方法
  28.                         uiProgressResponseListener.onUIResponseProgress(progressModel.getCurrentBytes(), progressModel.getContentLength(), progressModel.isDone());
  29.                     }
  30.                     break;
  31.                 default:
  32.                     super.handleMessage(msg);
  33.                     break;
  34.             }
  35.         }
  36.     }
  37.     //主线程Handler
  38.     private final Handler mHandler = new UIHandler(Looper.getMainLooper(), this);
  39.  
  40.     @Override
  41.     public void onResponseProgress(long bytesRead, long contentLength, boolean done) {
  42.         //通过Handler发送进度消息
  43.         Message message = Message.obtain();
  44.         message.obj = new ProgressModel(bytesRead, contentLength, done);
  45.         message.what = RESPONSE_UPDATE;
  46.         mHandler.sendMessage(message);
  47.     }
  48.  
  49.     /**
  50.      * UI层回调抽象方法
  51.      * @param bytesRead 当前读取响应体字节长度
  52.      * @param contentLength 总字节长度
  53.      * @param done 是否读取完成
  54.      */
  55.     public abstract void onUIResponseProgress(long bytesRead, long contentLength, boolean done);
  56. }

最简单的一步就是在我们的程序中使用了。为了方便Android Studio用户使用,我将其发布到了中央库。加入如下依赖即可

  1. dependencies {
  2.   compile 'cn.edu.zafu:coreprogress:0.0.1'
  3. }

注意OkHttp的依赖需要自己手动添加,这个库中OkHttp只是编译时依赖,并没有打包进去。

至于代码,也已经寄托在了github上,如果有bug,欢迎修正。https://github.com/lizhangqu/CoreProgress,具体使用方法github上也已经贴出来了。

如果依赖gradle不能下载的话可以直接从github上下代码。

这里贴一个简单的例子,布局文件,两个进度条用于显示进度

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.               xmlns:tools="http://schemas.android.com/tools"
  3.               android:layout_width="match_parent"
  4.               android:layout_height="match_parent"
  5.               android:orientation="vertical"
  6.               tools:context=".MainActivity">
  7.  
  8.     <ProgressBar
  9.         android:id="@+id/upload_progress"
  10.         style="?android:attr/progressBarStyleHorizontal"
  11.         android:layout_width="match_parent"
  12.         android:layout_height="wrap_content"
  13.         android:max="100"
  14.         android:progress="0"
  15.         />
  16.  
  17.     <Button
  18.         android:id="@+id/upload"
  19.         android:layout_width="match_parent"
  20.         android:layout_height="wrap_content"
  21.         android:text="Upload"/>
  22.  
  23.     <ProgressBar
  24.         android:id="@+id/download_progress"
  25.         style="?android:attr/progressBarStyleHorizontal"
  26.         android:layout_width="match_parent"
  27.         android:layout_height="wrap_content"
  28.         android:max="100"
  29.         android:progress="0"
  30.         />
  31.  
  32.     <Button
  33.         android:id="@+id/download"
  34.         android:layout_width="match_parent"
  35.         android:layout_height="wrap_content"
  36.         android:text="Download"/>
  37.  
  38.  
  39. </LinearLayout>

一个上传操作,一个下载操作,分别提供了UI层与非UI层回调的示例。最终代码中使用的监听器都是UI层的,因为我们要更新进度条。

  1. private void download() {
  2.         //这个是非ui线程回调,不可直接操作UI
  3.         final ProgressResponseListener progressResponseListener = new ProgressResponseListener() {
  4.             @Override
  5.             public void onResponseProgress(long bytesRead, long contentLength, boolean done) {
  6.                 Log.e("TAG", "bytesRead:" + bytesRead);
  7.                 Log.e("TAG", "contentLength:" + contentLength);
  8.                 Log.e("TAG", "done:" + done);
  9.                 if (contentLength != -1) {
  10.                     //长度未知的情况下回返回-1
  11.                     Log.e("TAG", (100 * bytesRead) / contentLength + "% done");
  12.                 }
  13.                 Log.e("TAG", "================================");
  14.             }
  15.         };
  16.  
  17.  
  18.         //这个是ui线程回调,可直接操作UI
  19.         final UIProgressResponseListener uiProgressResponseListener = new UIProgressResponseListener() {
  20.             @Override
  21.             public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
  22.                 Log.e("TAG", "bytesRead:" + bytesRead);
  23.                 Log.e("TAG", "contentLength:" + contentLength);
  24.                 Log.e("TAG", "done:" + done);
  25.                 if (contentLength != -1) {
  26.                     //长度未知的情况下回返回-1
  27.                     Log.e("TAG", (100 * bytesRead) / contentLength + "% done");
  28.                 }
  29.                 Log.e("TAG", "================================");
  30.                 //ui层回调
  31.                 downloadProgeress.setProgress((int) ((100 * bytesRead) / contentLength));
  32.                 //Toast.makeText(getApplicationContext(), bytesRead + " " + contentLength + " " + done, Toast.LENGTH_LONG).show();
  33.             }
  34.         };
  35.  
  36.         //构造请求
  37.         final Request request1 = new Request.Builder()
  38.                 .url("http://121.41.119.107:81/test/1.doc")
  39.                 .build();
  40.  
  41.         //包装Response使其支持进度回调
  42.         ProgressHelper.addProgressResponseListener(client, uiProgressResponseListener).newCall(request1).enqueue(new Callback() {
  43.             @Override
  44.             public void onFailure(Request request, IOException e) {
  45.                 Log.e("TAG", "error ", e);
  46.             }
  47.  
  48.             @Override
  49.             public void onResponse(Response response) throws IOException {
  50.                 Log.e("TAG", response.body().string());
  51.             }
  52.         });
  53.     }
  54.  
  55.     private void upload() {
  56.         File file = new File("/sdcard/1.doc");
  57.         //此文件必须在手机上存在,实际情况下请自行修改,这个目录下的文件只是在我手机中存在。
  58.  
  59.  
  60.         //这个是非ui线程回调,不可直接操作UI
  61.         final ProgressRequestListener progressListener = new ProgressRequestListener() {
  62.             @Override
  63.             public void onRequestProgress(long bytesWrite, long contentLength, boolean done) {
  64.                 Log.e("TAG", "bytesWrite:" + bytesWrite);
  65.                 Log.e("TAG", "contentLength" + contentLength);
  66.                 Log.e("TAG", (100 * bytesWrite) / contentLength + " % done ");
  67.                 Log.e("TAG", "done:" + done);
  68.                 Log.e("TAG", "================================");
  69.             }
  70.         };
  71.  
  72.  
  73.         //这个是ui线程回调,可直接操作UI
  74.         final UIProgressRequestListener uiProgressRequestListener = new UIProgressRequestListener() {
  75.             @Override
  76.             public void onUIRequestProgress(long bytesWrite, long contentLength, boolean done) {
  77.                 Log.e("TAG", "bytesWrite:" + bytesWrite);
  78.                 Log.e("TAG", "contentLength" + contentLength);
  79.                 Log.e("TAG", (100 * bytesWrite) / contentLength + " % done ");
  80.                 Log.e("TAG", "done:" + done);
  81.                 Log.e("TAG", "================================");
  82.                 //ui层回调
  83.                 uploadProgress.setProgress((int) ((100 * bytesWrite) / contentLength));
  84.                 //Toast.makeText(getApplicationContext(), bytesWrite + " " + contentLength + " " + done, Toast.LENGTH_LONG).show();
  85.             }
  86.         };
  87.  
  88.         //构造上传请求,类似web表单
  89.         RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
  90.                 .addFormDataPart("hello", "android")
  91.                 .addFormDataPart("photo", file.getName(), RequestBody.create(null, file))
  92.                 .addPart(Headers.of("Content-Disposition", "form-data; name=\"another\";filename=\"another.dex\""), RequestBody.create(MediaType.parse("application/octet-stream"), file))
  93.                 .build();
  94.  
  95.         //进行包装,使其支持进度回调
  96.         final Request request = new Request.Builder().url("http://121.41.119.107:81/test/result.php").post(ProgressHelper.addProgressRequestListener(requestBody, uiProgressRequestListener)).build();
  97.         //开始请求
  98.         client.newCall(request).enqueue(new Callback() {
  99.             @Override
  100.             public void onFailure(Request request, IOException e) {
  101.                 Log.e("TAG", "error ", e);
  102.             }
  103.  
  104.             @Override
  105.             public void onResponse(Response response) throws IOException {
  106.                 Log.e("TAG", response.body().string());
  107.             }
  108.         });
  109.  
  110.     }

需要特别注意的一点是文件的下载中如果文件大小未知,contentLength 会始终返回-1,对于已知文件大小的情况下,它返回的是实际文件大小。但是done只要在文件下载完成后才会返回true,可以使用两者的结合进行判断文件是否下载完成。

当然,我们进行进度的监听,最终还是会回调内部的接口,如果请求成功会回调onResponse,请求失败则回调onFailure,我们可以在onResponse中处理最终的结果。比如提示用户上传完成或者下载完成等等 。

还有一个细节需要注意就是连接的超时,读取与写入数据的超时时间的设置,在读取或者写入一些大文件的时候如果不设置这个参数可能会报异常,这里就随便设置了一下值,设得有点大,实际情况按需设置。

  1. //设置超时,不设置可能会报异常
  2.     private void initClient() {
  3.         client.setConnectTimeout(1000, TimeUnit.MINUTES);
  4.         client.setReadTimeout(1000, TimeUnit.MINUTES);
  5.         client.setWriteTimeout(1000, TimeUnit.MINUTES);
  6.     }

文件的上传需要服务器的配合,为了证明PHP是世界上最好的语言,服务器的操作使用PHP大法,其实就是简单的输出POST的内容和文件的信息,并将一个文件保存到了服务器当前目录下的file文件夹下。

  1. <?php
  2.  
  3. //打印POST传递的参数
  4. var_dump($_POST);
  5.  
  6. //打印文件信息
  7. var_dump($_FILES);
  8.  
  9. //将文件保存到当前目录下的file文件夹下
  10. move_uploaded_file($_FILES["photo"]["tmp_name"], "./file/".$_FILES["photo"]["name"]);
  11.  
  12. ?>

下面是运行结果,可以看到点击了上传或者下载后,进度条在不断更新。

20150903142847687.gif

以及对应的日志输出。

文件的上传,用数据说话

blob.png

文件的下载,同样是数据

blob.png

如果这篇文章对你有用,那么请点击下方的顶支持一个吧。

源代码什么的就不再贴了,直接从github上下载吧https://github.com/lizhangqu/CoreProgress

本站文章内容,部分来自于互联网,若侵犯了您的权益,请致邮件chuanghui423#sohu.com(请将#换为@)联系,我们会尽快核实后删除。
Copyright © 2006-2023 DBMNG.COM All Rights Reserved. Powered by DEVSOARTECH            豫ICP备11002312号-2

豫公网安备 41010502002439号