retrofit下载进度

来源:互联网 发布:电子贺卡软件 编辑:程序博客网 时间:2024/06/05 10:04
import java.io.IOException;import okhttp3.MediaType;import okhttp3.ResponseBody;import okio.Buffer;import okio.BufferedSource;import okio.ForwardingSource;import okio.Okio;import okio.Source;/** * Created by cy on 2017/7/15 0015. */public class DownResponse extends ResponseBody {    private ResponseBody responseBody;    private BufferedSource bufferedSource;    private downLoadProgressListener downLoadProgressListener;    public DownResponse(ResponseBody responseBody, downLoadProgressListener downLoadProgressListener) {        this.responseBody = responseBody;        this.downLoadProgressListener = downLoadProgressListener;    }    @Override    public MediaType contentType() {        return responseBody.contentType();    }    @Override    public long contentLength() {        return responseBody.contentLength();    }    @Override    public BufferedSource source() {        if (bufferedSource == null)            bufferedSource = Okio.buffer(source(responseBody.source()));        return bufferedSource;    }    private Source source(Source source) {        return new ForwardingSource(source) {            long totalBytesRead = 0L;            long contentLength = 0L;            @Override            public long read(Buffer sink, long byteCount) throws IOException {                long byteRead = super.read(sink, byteCount);                totalBytesRead += byteRead != -1 ? byteRead : 0;                if (contentLength == 0)                    contentLength = responseBody.contentLength();                if (downLoadProgressListener != null)                    downLoadProgressListener.progress(totalBytesRead, contentLength, byteRead == -1);                return byteRead;            }        };    }    public interface downLoadProgressListener {        void progress(long totalRead, long contentLength, boolean isDone);    }}

原创粉丝点击