【Android架構】基於MVP模式的Retrofit2+RXjava封裝之文件下載(二)

前言

上篇中咱們介紹了基於MVP的Retrofit2+RXjava封裝,這一篇咱們來講說文件下載的實現。java

咱們先在ApiServer定義好調用的接口git

@GET
    Observable<ResponseBody> downloadFile(@Url String fileUrl);
複製代碼

接着定義一個接口,下載成功後用來回調github

public interface FileView extends BaseView {

    void onSuccess(File file);
}
複製代碼

接着是Observer,建議與處理普通接口的Observer區分處理api

public abstract class FileObsever extends BaseObserver<ResponseBody> {
    private String path;

    public FileObsever(BaseView view, String path) {
        super(view);
        this.path = path;
    }

    @Override
    protected void onStart() {
    }

    @Override
    public void onComplete() {
    }

    @Override
    public void onSuccess(ResponseBody o) {

    }

    @Override
    public void onError(String msg) {

    }

    @Override
    public void onNext(ResponseBody o) {
        File file = FileUtil.saveFile(path, o);
        if (file != null && file.exists()) {
            onSuccess(file);
        } else {
            onErrorMsg("file is null or file not exists");
        }
    }

    @Override
    public void onError(Throwable e) {
        onErrorMsg(e.toString());
    }


    public abstract void onSuccess(File file);

    public abstract void onErrorMsg(String msg);
}

複製代碼

FileUtil 注:若是須要寫入文件的進度,能夠在將這段方法放在onNext中,在FileObsever這個類寫個方法,而後回調。網絡

public static File saveFile(String filePath, ResponseBody body) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        File file = null;
        try {
            if (filePath == null) {
                return null;
            }
            file = new File(filePath);
            if (file == null || !file.exists()) {
                file.createNewFile();
            }


            long fileSize = body.contentLength();
            long fileSizeDownloaded = 0;
            byte[] fileReader = new byte[4096];

            inputStream = body.byteStream();
            outputStream = new FileOutputStream(file);

            while (true) {
                int read = inputStream.read(fileReader);
                if (read == -1) {
                    break;
                }
                outputStream.write(fileReader, 0, read);
                fileSizeDownloaded += read;

            }

            outputStream.flush();


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return file;
    }
複製代碼

下來是FilePresenter架構

public class FilePresenter extends BasePresenter<FileView> {
    public FilePresenter(FileView baseView) {
        super(baseView);
    }

    public void downFile(String url, final String path) {

        addDisposable(apiServer.downloadFile(url), new FileObsever(baseView, path) {


            @Override
            public void onSuccess(File file) {
                if (file != null && file.exists()) {
                    baseView.onSuccess(file);
                } else {
                    baseView.showError("file is null");
                }
            }

            @Override
            public void onErrorMsg(String msg) {
                baseView.showError(msg);

            }
        });

    }
    }
複製代碼

最後在Activity中調用app

private void downFile() {
        String url = "http://download.sdk.mob.com/apkbus.apk";

        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {// 檢查是否有存儲卡
            dir = Environment.getExternalStorageDirectory() + "/ceshi/";
            File dirFile = new File(dir);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
        }
        presenter.downFile(url, dir + "app-debug.apk");
    }
複製代碼

就在我覺得萬事大吉的時候,APP崩潰了,錯誤信息以下: [圖片上傳失敗...(image-39e2a7-1532052138950)]ide

原來是加入日誌監聽器,會致使每次都把整個文件加載到內存,那咱們就去掉這個post

修改FilePresenter#downFile以下:ui

public void downFile(String url, final String path) {

        OkHttpClient client = new OkHttpClient.Builder().build();
        Retrofit retrofit = new Retrofit.Builder().client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl("https://wawa-api.vchangyi.com/").build();

        apiServer = retrofit.create(ApiServer.class);

        addDisposable(apiServer.downloadFile(url), new FileObsever(baseView, path) {
            @Override
            public void onSuccess(File file) {
                if (file != null && file.exists()) {
                    baseView.onSuccess(file);
                } else {
                    baseView.showError("file is null");
                }
            }

            @Override
            public void onErrorMsg(String msg) {
                baseView.showError(msg);

            }
        });
    }
複製代碼

此次卻是下載成功了,不過官方建議10M以上的文件用Streaming標籤,咱們加上Streaming標籤試試 修改ApiServer

@Streaming
    @GET
    /** * 大文件官方建議用 @Streaming 來進行註解,否則會出現IO異常,小文件能夠忽略不注入 */
    Observable<ResponseBody> downloadFile(@Url String fileUrl);
複製代碼

此次又崩潰了,錯誤信息以下: [圖片上傳失敗...(image-fc8c28-1532052138951)]

這是怎麼回事,咱們網絡請求是在子線程啊。無奈之下只得翻翻官方文檔,原來使用該註解表示響應用字節流的形式返回.若是沒使用該註解,默認會把數據所有載入到內存中。咱們能夠在主線程中處理寫入文件(不建議),但不能在主線程中處理字節流。因此,咱們須要將處理字節流、寫入文件都放在子線程中。

因而,修改FilePresenter#downFile以下:

OkHttpClient client = new OkHttpClient.Builder().build();
        Retrofit retrofit = new Retrofit.Builder().client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl("https://wawa-api.vchangyi.com/").build();

        apiServer = retrofit.create(ApiServer.class);
          apiServer
                .downloadFile(url)
                .map(new Function<ResponseBody, String>() {
                    @Override
                    public String apply(ResponseBody body) throws Exception {
                        File file = FileUtil.saveFile(path, body);
                        return file.getPath();
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new FileObserver(baseView) {
                    @Override
                    public void onSuccess(File file) {
                        baseView.onSuccess(file);
                    }

                    @Override
                    public void onError(String msg) {
                        baseView.showError(msg);
                    }
                });
複製代碼

這樣,下載文件算是完成了,好像還缺點什麼?對,缺個下載進度,還記得攔截器嗎,咱們能夠從這裏入手:

public class ProgressResponseBody extends ResponseBody {
    private ResponseBody responseBody;
    private BufferedSource bufferedSource;
    private ProgressListener progressListener;

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


    @Nullable
    @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;
                progressListener.onProgress(responseBody.contentLength(), totalBytesRead);
                return bytesRead;
            }
        };
    }

    public interface ProgressListener {
        void onProgress(long totalSize, long downSize);
    }
}

複製代碼

在BaseView 中定義接口,我的建議放在BaseView 中,在BaseActivity中實現BaseView,方便複用

/** * 下載進度 * * @param totalSize * @param downSize */

    void onProgress(long totalSize, long downSize);
複製代碼

再次修改FilePresenter#downFile以下:

public void downFile(final String url, final String path) {


        OkHttpClient client = new OkHttpClient.Builder()
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Response response = chain.proceed(chain.request());
                        return response.newBuilder().body(new ProgressResponseBody(response.body(),
                                new ProgressResponseBody.ProgressListener() {
                                    @Override
                                    public void onProgress(long totalSize, long downSize) {
                                        baseView.onProgress(totalSize, downSize);
                                    }
                                })).build();
                    }
                }).build();

        Retrofit retrofit = new Retrofit.Builder().client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl("https://wawa-api.vchangyi.com/").build();

        apiServer = retrofit.create(ApiServer.class);

        apiServer
                .downloadFile(url)
                .map(new Function<ResponseBody, String>() {
                    @Override
                    public String apply(ResponseBody body) throws Exception {
                        File file = FileUtil.saveFile(path, body);
                        return file.getPath();
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new FileObserver(baseView) {
                    @Override
                    public void onSuccess(File file) {
                        baseView.onSuccess(file);
                    }

                    @Override
                    public void onError(String msg) {
                        baseView.showError(msg);
                    }
                });


    }
複製代碼

至此,使用Retrofit下載文件暫時告一段落。

你的承認,是我堅持更新博客的動力,若是以爲有用,就請點個贊,謝謝

項目源碼

相關文章
相關標籤/搜索