Retrofit使用教程:通过Retrofit下载大文件并监听下载进度

前言

在开发项目中不免会遇到下载文件的需求,如果正好使用的是Retrofit网络框架又不想使用其它网络框架或者手写的HttpUrlConnection,那只好在Retrofit的基础上封装下载。

功能描述

  • 支持下载大文件
  • 支持多个页面监听
  • 支持进度回调监听

使用说明

  • 例一
    通过AppDownLoadHelper设置下载地址、存储位置即可下载文件。
    还可以配置AppProgressListener或者设置Tag来满足更多的需求。
public class MainActivity extends AppCompatActivity {

    private Button mDownButton;

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDownButton = (Button) findViewById(R.id.main_button_down);
        mDownButton.setOnClickListener(mListener);

        findViewById(R.id.main_button_start).setOnClickListener(new View.OnClickListener() {@Override public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, Main2Activity.class);
                startActivity(intent);
            }
        });
    }

    View.OnClickListener mListener = new View.OnClickListener() {@Override public void onClick(View view) {

            AppDownLoadHelper helper = AppDownLoadManager.getInstance().getHelperByTag("xx");
            if (helper != null) {
                AppDownLoadManager.getInstance().cancelHelperByTag("xx");
                mDownButton.setText("下载");
                return;
            }

            new AppDownLoadHelper.Builder().setPath(SDCardUtil.getLogCacheDir(AppApplication.getContext()) + "/xxx1.apk").setTag("xx").setUrl("http://dl.play.91.com/bigdata/com.ilongyuan.voez.baidu_v1.0.4.apk").setDownLoadListener(new AppProgressListener() {@Override public void onStart() {
                    Log.i("tag", "========开始");
                    mDownButton.setText("0%");
                }

                @Override public void update(long bytesRead, long contentLength, boolean done) {
                    int read = (int)(bytesRead * 100f / contentLength);
                    Log.i("tag", "========" + read);
                    mDownButton.setText(read + "%");
                }

                @Override public void onCompleted() {
                    mDownButton.setText("完成");
                    Log.i("tag", "========" + Thread.currentThread().getName());
                }

                @Override public void onError(String err) {
                    mDownButton.setText("失败");
                    Log.i("tag", "========失败" + err);
                }
            }).create().execute();
        }
    };

    @Override protected void onDestroy() {
        super.onDestroy();
        AppDownLoadManager.getInstance().unsubscribe();
    }
}
  • 例二
    根据Tag获取指定的AppDownLoadHelper,AppDownLoadHelper是下载的总控制器只要获取到它就可以对正在下载的文件进行取消、进度监听操作。
public class Main2Activity extends AppCompatActivity {

    private AppDownLoadHelper mHelper;
    private Button mDownButton;

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        mDownButton = (Button) findViewById(R.id.main2_button_down);

        mHelper = AppDownLoadManager.getInstance().getHelperByTag("xx");
        if (mHelper != null) {
            mHelper.registerListener(mProgressLinstener);
        }
    }

    AppProgressListener mProgressLinstener = new AppProgressListener() {
        @Override public void onStart() {}

        @Override public void update(long bytesRead, long contentLength, boolean done) {
            int read = (int)(bytesRead * 100f / contentLength);
            mDownButton.setText(read + "%");
        }

        @Override public void onCompleted() {
            mDownButton.setText("完成");
        }

        @Override public void onError(String err) {}
    };

    @Override protected void onDestroy() {
        super.onDestroy();
        if (mHelper != null) {
            mHelper.unRegisterListener(mProgressLinstener);
        }
    }
}

源码解读

  • 一、定义下载器:负责下载功能
public class AppDownLoadHelper {

    省略...

    private AppDownLoadHelper() {
        mDownloadListeners = new HashSet < >();
        mManager = AppDownLoadManager.getInstance();
    }

    public void setCancel(boolean cancel) {
        isCancel = cancel;
    }

    public void setmUrl(String url) {
        if (url != null) {
            int lastIndex = url.lastIndexOf("/");
            if (lastIndex != -1) {
                mApkName = url.substring(lastIndex + 1);
                mBaseUrl = url.substring(0, lastIndex + 1);
            }
        }
    }

    /**
     * 默认分配tag
     */
    public void setTag(Object tag) {
        if (tag != null) {
            mTag = tag;
        } else {
            mTag = UUID.randomUUID().toString();
        }
    }

    public void registerListener(AppProgressListener listener) {
        mDownloadListeners.add(listener);
    }

    public void unRegisterListener(AppProgressListener listener) {
        mDownloadListeners.remove(listener);
    }

    private OkHttpClient getDefaultOkHttp() {
        return getBuilder().build();
    }

    private OkHttpClient.Builder getBuilder() {
        AppSigningInterceptor signingInterceptor = new AppSigningInterceptor();
        signingInterceptor.setProgressListener(mListener);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(signingInterceptor);
        builder.connectTimeout(mConnectionTimeout, TimeUnit.SECONDS);
        builder.readTimeout(mReadTimeout, TimeUnit.SECONDS);
        return builder;
    }

    public static class Builder {
        private AppProgressListener mListener;
        private String mUrl;
        private String mPath;
        private int mConnectionTimeout;
        private int mReadTimeout;
        private Object mTag;

        public Builder() {
            this.mConnectionTimeout = CONNECTION_TIMEOUT;
            this.mReadTimeout = READ_DOWN_TIMEOUT;
        }

        /**
         * 设置任务标记
         */
        public Builder setTag(Object tag) {
            this.mTag = tag;
            return this;
        }

        /**
         * 设置下载文件的URL
         */
        public Builder setUrl(String url) {
            this.mUrl = url;
            return this;
        }

        /**
         * 设置HTTP请求连接超时时间,默认10s
         */
        public Builder setConnectionTimeout(int timeout) {
            this.mConnectionTimeout = timeout;
            return this;
        }

        /**
         * 设置HTTP请求数据读取超时时间,默认20s
         */
        public Builder setReadTimeout(int timeout) {
            this.mReadTimeout = timeout;
            return this;
        }

        /**
         * 设置下载文件保存地址,使用绝对路径
         */
        public Builder setPath(String path) {
            this.mPath = path;
            return this;
        }

        /**
         * 设置下载监听
         */
        public Builder setDownLoadListener(AppProgressListener listener) {
            this.mListener = listener;
            return this;
        }

        /**
         * 创建一个本地任务
         */
        public AppDownLoadHelper create() {
            final AppDownLoadHelper helper = new AppDownLoadHelper();
            helper.mConnectionTimeout = mConnectionTimeout;
            helper.mReadTimeout = mReadTimeout;
            helper.mPath = mPath;
            helper.setTag(mTag);
            helper.setmUrl(mUrl);
            if (mListener != null) {
                helper.mDownloadListeners.add(mListener);
            }
            return helper;
        }
    }

    public void execute() {
        mManager.addHelper(this);
        mAdapter = new Retrofit.Builder().baseUrl(mBaseUrl).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).client(getDefaultOkHttp()).build();
        mUploadService = mAdapter.create(AppDownloadService.class);

        final long startTime = System.currentTimeMillis();
        mUploadService.download(mApkName).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new Subscriber < ResponseBody > () {

            @Override public void onCompleted() {
                if (isCancel) {
                    mListener.onError("cancel");
                } else if (mListener != null) {
                    mListener.onCompleted();
                }
            }

            @Override public void onError(Throwable e) {
                if (mListener != null) {
                    mListener.onError(e.getMessage());
                }
            }

            @Override public void onNext(ResponseBody responseBody) {
                Log.i("AppDownLoadHelper", "========next" + responseBody.contentLength());

                省略... 数据存储本地操作
                long endTime = System.currentTimeMillis();
                Log.i("AppDownLoadHelper", "========time" + (endTime - startTime));
            }
        });

        if (mListener != null) {
            mListener.onStart();
        }
    }
}
  • 二、定义下载管理者:通过Map管理单个或多个下载器,并分发每个下载器的状态。
public class AppDownLoadManager {

    public static final int START = 1;
    public static final int PROGRESSING = 2;
    public static final int COMPLETED = 3;
    public static final int EXCEPTION = 4;

    private static AppDownLoadManager mInstance;
    private ConcurrentHashMap <Object, AppDownLoadHelper> mTagToHelpers;
    private Handler mUIHandler;

    private AppDownLoadManager() {
        mTagToHelpers = new ConcurrentHashMap <Object, AppDownLoadHelper> ();
        mUIHandler = new UIHandler(mTagToHelpers);
    }

    public synchronized static AppDownLoadManager getInstance() {
        if (mInstance == null) {
            mInstance = new AppDownLoadManager();
        }
        return mInstance;
    }

    public void addHelper(final AppDownLoadHelper helper) {
        if (helper == null) return;

        helper.mListener = new AppProgressListener() {@Override public void onStart() {
                Message message = mUIHandler.obtainMessage();
                message.obj = helper.mTag;
                message.what = START;
                message.sendToTarget();
            }

            @Override public void update(long bytesRead, long contentLength, boolean done) {
                Message message = mUIHandler.obtainMessage();
                Bundle bundle = new Bundle();
                bundle.putLong("bytesRead", bytesRead);
                bundle.putLong("contentLength", contentLength);
                bundle.putBoolean("done", done);
                message.setData(bundle);
                message.obj = helper.mTag;
                message.what = PROGRESSING;
                message.sendToTarget();
            }

            @Override public void onCompleted() {
                Message message = mUIHandler.obtainMessage();
                message.obj = helper.mTag;
                message.what = COMPLETED;
                message.sendToTarget();
            }

            @Override public void onError(String err) {
                Message message = mUIHandler.obtainMessage();
                message.obj = helper.mTag;
                message.what = EXCEPTION;
                Bundle bundle = new Bundle();
                bundle.putString("err", err);
                message.setData(bundle);
                message.sendToTarget();
            }
        };
        mTagToHelpers.put(helper.mTag, helper);
    }

    public AppDownLoadHelper getHelperByTag(Object tag) {
        return tag == null ? null: mTagToHelpers.get(tag);
    }

    public void cancelHelperByTag(Object tag) {
        AppDownLoadHelper helper = mTagToHelpers.get(tag);
        if (helper != null) {
            helper.setCancel(true);
            helper.mDownloadListeners.clear();
            mTagToHelpers.remove(tag);
        }
    }

    private static class UIHandler extends Handler {
        private ConcurrentHashMap < Object,
        AppDownLoadHelper > mTagToHelpers;

        public UIHandler(ConcurrentHashMap < Object, AppDownLoadHelper > tagToHelpers) {
            mTagToHelpers = tagToHelpers;
        }

        @Override public void handleMessage(Message msg) {
            super.handleMessage(msg);

            String tagID = (String) msg.obj;
            AppDownLoadHelper helper = mTagToHelpers.get(tagID);
            if (helper == null) return;

            switch (msg.what) {
            case START:
                //任务开始
                for (AppProgressListener listener:
                helper.mDownloadListeners) {
                    listener.onStart();
                }
                break;

            case PROGRESSING:
                //任务进度更新
                Bundle data = msg.getData();
                for (AppProgressListener listener: helper.mDownloadListeners) {
                    listener.update(data.getLong("bytesRead"), data.getLong("contentLength"), data.getBoolean("done"));
                }
                break;

            case COMPLETED:
                //任务完成
                for (AppProgressListener listener:
                helper.mDownloadListeners) {
                    listener.onCompleted();
                }
                helper.mDownloadListeners.clear();
                mTagToHelpers.remove(tagID);
                break;

            case EXCEPTION:
                //任务发生异常
                Bundle e = msg.getData();
                for (AppProgressListener listener: helper.mDownloadListeners) {
                    listener.onError(e.getString("err"));
                }
                helper.mDownloadListeners.clear();
                helper.setCancel(true);
                mTagToHelpers.remove(tagID);
                break;

            default:
                break;
            }
        }
    }

    public void unsubscribe() {
        for (Object key:
        mTagToHelpers.keySet()) {
            AppDownLoadHelper appDownLoadHelper = mTagToHelpers.get(key);
            appDownLoadHelper.setCancel(true);
            appDownLoadHelper.mDownloadListeners.clear();
            mTagToHelpers.remove(key);
        }
    }
}
  • 三、网络请求API
public interface AppDownloadService {
    @Streaming
    @GET("{url}") 
    Observable <ResponseBody> download(@Path("url")String apkName);
}
  • 四、下载进度回调接口
public interface AppProgressListener {
    void onStart();
    void update(long bytesRead, long contentLength, boolean done);
    void onCompleted();
    void onError(String err);
}
  • 五、Retrofit使用中的拦截器:用于对下载进度的拦截
public class AppSigningInterceptor implements Interceptor {

    public AppProgressListener mProgressListener;
    public void setProgressListener(AppProgressListener p) {
        mProgressListener = p;
    }

    @Override public Response intercept(Chain chain) throws IOException {

        Request oldRequest = chain.request();
        // 添加新的参数
        HttpUrl.Builder authorizedUrlBuilder = oldRequest.url().newBuilder().scheme(oldRequest.url().scheme()).host(oldRequest.url().host());

        // 设置统一请求参数
        Request.Builder newRequest = oldRequest.newBuilder().method(oldRequest.method(), oldRequest.body())
        .url(authorizedUrlBuilder.build());

        if (mProgressListener != null) {
            Response originalResponse = chain.proceed(newRequest.build());
            return originalResponse.newBuilder().body(new ProgressResponseBody(originalResponse.body(), mProgressListener)).build();
        }
        return chain.proceed(newRequest.build());
    }
}
  • 六、自定义ResponseBody:通过配置在拦截器里对下载进度监听
public class ProgressResponseBody extends ResponseBody {

    private final ResponseBody responseBody;
    private final AppProgressListener progressListener;
    private BufferedSource bufferedSource;

    public ProgressResponseBody(ResponseBody responseBody, AppProgressListener progressListener) {
        this.responseBody = responseBody;
        this.progressListener = progressListener;
    }

    @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;

            @Override public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                totalBytesRead += bytesRead != -1 ? bytesRead: 0;
                progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
                return bytesRead;
            }
        };
    }
}

github源码下载

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,684评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,143评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,214评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,788评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,796评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,665评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,027评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,679评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,346评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,664评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,766评论 1 331
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,412评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,015评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,974评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,073评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,501评论 2 343

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,596评论 18 139
  • #Android 基础知识点总结 ---------- ##1.adb - android debug bridg...
    Mythqian阅读 3,250评论 2 11
  • 前言RxJava和Retrofit也火了一段时间了,不过最近一直在学习ReactNative和Node相关的姿势,...
    AFinalStone阅读 536评论 0 0
  • 面向对象的六大原则 单一职责原则 所谓职责是指类变化的原因。如果一个类有多于一个的动机被改变,那么这个类就具有多于...
    JxMY阅读 924评论 1 3
  • 因为之前也买了几个币种,故而对这次币市的震动也比较关注。确实让我看到很多之前不曾看到的东西,不止一次提醒投资有风险...
    晓晗秋月阅读 86评论 1 0