/*断点续传下载接口*/
@Streaming/*大文件需要加入这个判断,防止下载过程中写入到内存中*/
@GET
Observable<ResponseBody> download(@Header("RANGE") String start, @Url String url);
/**
* 自定义进度的body
* @author wzg
*/
public class DownloadResponseBody extends ResponseBody {
private ResponseBody responseBody;
private DownloadProgressListener progressListener;
private BufferedSource bufferedSource;
public DownloadResponseBody(ResponseBody responseBody, DownloadProgressListener progressListener) {
this.responseBody = responseBody;
this.progressListener = progressListener;
}
@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;
@Override
public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead = super.read(sink, byteCount);
// read() returns the number of bytes read, or -1 if this source is exhausted.
totalBytesRead += bytesRead != -1 ? bytesRead : 0;
if (null != progressListener) {
progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
}
return bytesRead;
}
};
}
}
/**
* 成功回调处理
* Created by WZG on 2016/10/20.
*/
public interface DownloadProgressListener {
/**
* 下载进度
* @param read
* @param count
* @param done
*/
void update(long read, long count, boolean done);
}
/**
* 成功回调处理
* Created by WZG on 2016/10/20.
*/
public class DownloadInterceptor implements Interceptor {
private DownloadProgressListener listener;
public DownloadInterceptor(DownloadProgressListener listener) {
this.listener = listener;
}
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new DownloadResponseBody(originalResponse.body(), listener))
.build();
}
}
public class DownInfo {
/*存储位置*/
private String savePath;
/*下载url*/
private String url;
/*基础url*/
private String baseUrl;
/*文件总长度*/
private long countLength;
/*下载长度*/
private long readLength;
/*下载唯一的HttpService*/
private HttpService service;
/*回调监听*/
private HttpProgressOnNextListener listener;
/*超时设置*/
private int DEFAULT_TIMEOUT = 6;
/*下载状态*/
private DownState state;
}
public enum DownState {
START,
DOWN,
PAUSE,
STOP,
ERROR,
FINISH,
}
/**
* 下载过程中的回调处理
* Created by WZG on 2016/10/20.
*/
public abstract class HttpProgressOnNextListener<T> {
/**
* 成功后回调方法
* @param t
*/
public abstract void onNext(T t);
/**
* 开始下载
*/
public abstract void onStart();
/**
* 完成下载
*/
public abstract void onComplete();
/**
* 下载进度
* @param readLength
* @param countLength
*/
public abstract void updateProgress(long readLength, long countLength);
/**
* 失败或者错误方法
* 主动调用,更加灵活
* @param e
*/
public void onError(Throwable e){
}
/**
* 暂停下载
*/
public void onPuase(){
}
/**
* 停止下载销毁
*/
public void onStop(){
}
}
/**
* 用于在Http请求开始时,自动显示一个ProgressDialog
* 在Http请求结束是,关闭ProgressDialog
* 调用者自己对请求数据进行处理
* Created by WZG on 2016/7/16.
*/
public class ProgressDownSubscriber<T> extends Subscriber<T> implements DownloadProgressListener {
//弱引用结果回调
private WeakReference<HttpProgressOnNextListener> mSubscriberOnNextListener;
/*下载数据*/
private DownInfo downInfo;
public ProgressDownSubscriber(DownInfo downInfo) {
this.mSubscriberOnNextListener = new WeakReference<>(downInfo.getListener());
this.downInfo=downInfo;
}
/**
* 订阅开始时调用
* 显示ProgressDialog
*/
@Override
public void onStart() {
if(mSubscriberOnNextListener.get()!=null){
mSubscriberOnNextListener.get().onStart();
}
downInfo.setState(DownState.START);
}
/**
* 完成,隐藏ProgressDialog
*/
@Override
public void onCompleted() {
if(mSubscriberOnNextListener.get()!=null){
mSubscriberOnNextListener.get().onComplete();
}
downInfo.setState(DownState.FINISH);
}
/**
* 对错误进行统一处理
* 隐藏ProgressDialog
*
* @param e
*/
@Override
public void onError(Throwable e) {
/*停止下载*/
HttpDownManager.getInstance().stopDown(downInfo);
if(mSubscriberOnNextListener.get()!=null){
mSubscriberOnNextListener.get().onError(e);
}
downInfo.setState(DownState.ERROR);
}
/**
* 将onNext方法中的返回结果交给Activity或Fragment自己处理
*
* @param t 创建Subscriber时的泛型类型
*/
@Override
public void onNext(T t) {
if (mSubscriberOnNextListener.get() != null) {
mSubscriberOnNextListener.get().onNext(t);
}
}
@Override
public void update(long read, long count, boolean done) {
if(downInfo.getCountLength()>count){
read=downInfo.getCountLength()-count+read;
}else{
downInfo.setCountLength(count);
}
downInfo.setReadLength(read);
if (mSubscriberOnNextListener.get() != null) {
/*接受进度消息,造成UI阻塞,如果不需要显示进度可去掉实现逻辑,减少压力*/
rx.Observable.just(read).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
/*如果暂停或者停止状态延迟,不需要继续发送回调,影响显示*/
if(downInfo.getState()==DownState.PAUSE||downInfo.getState()==DownState.STOP)return;
downInfo.setState(DownState.DOWN);
mSubscriberOnNextListener.get().updateProgress(aLong,downInfo.getCountLength());
}
});
}
}
}
/**
* 获取单例
* @return
*/
public static HttpDownManager getInstance() {
if (INSTANCE == null) {
synchronized (HttpDownManager.class) {
if (INSTANCE == null) {
INSTANCE = new HttpDownManager();
}
}
}
return INSTANCE;
}
/*回调sub队列*/
private HashMap<String,ProgressDownSubscriber> subMap;
/*单利对象*/
private volatile static HttpDownManager INSTANCE;
private HttpDownManager(){
downInfos=new HashSet<>();
subMap=new HashMap<>();
}
/**
* 开始下载
*/
public void startDown(DownInfo info){
/*正在下载不处理*/
if(info==null||subMap.get(info.getUrl())!=null){
return;
}
/*添加回调处理类*/
ProgressDownSubscriber subscriber=new ProgressDownSubscriber(info);
/*记录回调sub*/
subMap.put(info.getUrl(),subscriber);
/*获取service,多次请求公用一个sercie*/
HttpService httpService;
if(downInfos.contains(info)){
httpService=info.getService();
}else{
DownloadInterceptor interceptor = new DownloadInterceptor(subscriber);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
//手动创建一个OkHttpClient并设置超时时间
builder.connectTimeout(info.getConnectionTime(), TimeUnit.SECONDS);
builder.addInterceptor(interceptor);
Retrofit retrofit = new Retrofit.Builder()
.client(builder.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(info.getBaseUrl())
.build();
httpService= retrofit.create(HttpService.class);
info.setService(httpService);
}
/*得到rx对象-上一次下載的位置開始下載*/
httpService.download("bytes=" + info.getReadLength() + "-",info.getUrl())
/*指定线程*/
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
/*失败后的retry配置*/
.retryWhen(new RetryWhenNetworkException())
/*读取下载写入文件*/
.map(new Func1<ResponseBody, DownInfo>() {
@Override
public DownInfo call(ResponseBody responseBody) {
try {
writeCache(responseBody,new File(info.getSavePath()),info);
} catch (IOException e) {
/*失败抛出异常*/
throw new HttpTimeException(e.getMessage());
}
return info;
}
})
/*回调线程*/
.observeOn(AndroidSchedulers.mainThread())
/*数据回调*/
.subscribe(subscriber);
}
/**
* 写入文件
* @param file
* @param info
* @throws IOException
*/
public void writeCache(ResponseBody responseBody,File file,DownInfo info) throws IOException{
if (!file.getParentFile().exists())
file.getParentFile().mkdirs();
long allLength;
if (info.getCountLength()==0){
allLength=responseBody.contentLength();
}else{
allLength=info.getCountLength();
}
FileChannel channelOut = null;
RandomAccessFile randomAccessFile = null;
randomAccessFile = new RandomAccessFile(file, "rwd");
channelOut = randomAccessFile.getChannel();
MappedByteBuffer mappedBuffer = channelOut.map(FileChannel.MapMode.READ_WRITE,
info.getReadLength(),allLength-info.getReadLength());
byte[] buffer = new byte[1024*8];
int len;
int record = 0;
while ((len = responseBody.byteStream().read(buffer)) != -1) {
mappedBuffer.put(buffer, 0, len);
record += len;
}
responseBody.byteStream().close();
if (channelOut != null) {
channelOut.close();
}
if (randomAccessFile != null) {
randomAccessFile.close();
}
}
/**
* 停止下载
*/
public void stopDown(DownInfo info){
if(info==null)return;
info.setState(DownState.STOP);
info.getListener().onStop();
if(subMap.containsKey(info.getUrl())) {
ProgressDownSubscriber subscriber=subMap.get(info.getUrl());
subscriber.unsubscribe();
subMap.remove(info.getUrl());
}
/*同步数据库*/
}
/**
* 暂停下载
* @param info
*/
public void pause(DownInfo info){
if(info==null)return;
info.setState(DownState.PAUSE);
info.getListener().onPuase();
if(subMap.containsKey(info.getUrl())){
ProgressDownSubscriber subscriber=subMap.get(info.getUrl());
subscriber.unsubscribe();
subMap.remove(info.getUrl());
}
/*这里需要讲info信息写入到数据中,可自由扩展,用自己项目的数据库*/
}
/**
* 停止全部下载
*/
public void stopAllDown(){
for (DownInfo downInfo : downInfos) {
stopDown(downInfo);
}
subMap.clear();
downInfos.clear();
}
/**
* 暂停全部下载
*/
public void pauseAll(){
for (DownInfo downInfo : downInfos) {
pause(downInfo);
}
subMap.clear();
downInfos.clear();
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有