Retrofit+RXJava_多线程下载视频列表

BaseService:

public class BaseService {

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl("http://result.eolinker.com/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create());

    public static  S createService(Class serviceClass) {
        Retrofit retrofit = builder.client(httpClient.build()).build();
        return retrofit.create(serviceClass);
    }
}

API:

public interface RetrofitAPI {
    @Streaming
    @GET
    Observable download(@Header("RANGE") String start, @Url String url);
}

Model接口:

public interface IDownLoadModel {
        void getData(String start,String url,String url2,GetCallback callback);
        interface GetCallback{
            void GetComplete(ResponseBody responseBody);
        }
    }

Model实现类:

public class DownLoadModel implements IDownLoadModel {

    String url3 = "";
    private static final String DOWNLOAD_INIT = "1";
    private static final String DOWNLOAD_ING = "2";
    private static final String DOWNLOAD_PAUSE = "3";
    private String stateDownload = DOWNLOAD_INIT;//当前线程状态
    private long pro;
    public Progress progress;

    @Override
    public void getData(String start, String url, final String url2, GetCallback callback) {

        this.url3 = url;
        BaseService.createService(RetrofitAPI.class).download(start, url3)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {

                        final long l = responseBody.contentLength();
                        downloadTask(l, url2);
                    }
                });
    }

    public void downloadTask(final long length, String url2) {
        final File file = new File(url2);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        MainActivity.MAX_SIZE = length;
        //例如  1000kb  3   333
        int threadNum = 5;
        long blockSize = length / threadNum;
//        //四舍五入---  让一个数字+0。5在四舍五入 就变成 向上取整
        //计算出下载块以后   创建线程执行下载操作
        for (int i = 0; i < threadNum; i++) {
            //计算开始位置
            final long startPosition = blockSize * i;
            //让最后一个线程下载的大小是正好的,  总长度 - 除了最后一个块的大小和
            if (i == threadNum - 1) {
                blockSize = length - blockSize * (threadNum - 1);
            }
            String range = "bytes=" + startPosition + "-" + (startPosition + blockSize - 1);

            BaseService.createService(RetrofitAPI.class).download(range, url3)
                    .subscribeOn(Schedulers.io())
                    .observeOn(Schedulers.io())
                    .subscribe(new Observer() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(ResponseBody responseBody) {

                            BufferedInputStream bis = new BufferedInputStream(responseBody.byteStream());
                            RandomAccessFile raf = null;
                            try {
                                raf = new RandomAccessFile(file, "rwd");
                                raf.seek(startPosition);
                                byte[] buff = new byte[1024 * 8];
                                int len = 0;
                                while ((len = bis.read(buff)) != -1) {
                                    raf.write(buff, 0, len);
                                    pro += len;
                                    final int l = (int) (pro * 100 / length);

                                    handler.sendEmptyMessage(l);
                                    Log.i("=======l", "onNext: " + l);
                                    DownLoadActivity.progre = l;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    });

        }
    }


    public void setProgress(Progress progress) {
        this.progress = progress;
    }

    public interface Progress{
        void updateProgress(int progress);
    }

    protected void onPause() {
        stateDownload = DOWNLOAD_PAUSE;
    }

    /**
     * 继续下载
     */
    protected void onStart() {

        synchronized (DOWNLOAD_PAUSE) {
            stateDownload = DOWNLOAD_ING;
            DOWNLOAD_PAUSE.notifyAll();
        }
    }

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {

                    progress.updateProgress(msg.what);

        }
    };
}


View接口:

public interface IDownLoadView {
    void getProgress(int a);

    void getData(ResponseBody responseBody);
}

Presenter:

public class DownLoadPresenter  implements BasePresenter {

    SoftReference srf;
    DownLoadModel model;


    public DownLoadPresenter(IDownLoadView view) {
        model = new DownLoadModel();
        attch(view);
    }

    public void down(final String start, final String url, final String url2) {

        model.getData(start, url, url2, new IDownLoadModel.GetCallback() {
            @Override
            public void GetComplete(ResponseBody responseBody) {
                srf.get().getData(responseBody);
            }
        });

        model.setProgress(new DownLoadModel.Progress() {
            @Override
            public void updateProgress(int progress) {
                srf.get().getProgress(progress);
            }
        });

    }

    @Override
    public void attch(IDownLoadView view) {
        srf = new SoftReference(view);
    }

    @Override
    public void deatch() {
        srf.clear();
    }
}

Activity:

public class DownLoadActivity extends BaseActivity implements IDownLoadView {

    @BindView(R.id.wb)
    VideoView wb;
    @BindView(R.id.btn)
    Button btn;
    @BindView(R.id.pro)
    ProgressBar pro;
    @BindView(R.id.tv)
    TextView tv;
    private String uri;
    public static long progre;
    private String s;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_down_load);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        uri = intent.getStringExtra("uri");
        wb.setMediaController(new MediaController(this));
//        wb.setVideoURI(Uri.parse(uri));

        wb.requestFocus();


        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                s = getCacheDir() + "haha1.mp4";
                presenter.down(String.valueOf(0), uri, s);

            }
        });
    }

    @Override
    void createPresenter() {
        presenter = new DownLoadPresenter(this);
    }

    @Override
    public void getProgress(int a) {
        pro.setProgress(a);
        tv.setText(a+"%");
        if(tv.getText().toString().equals("100%")){
            Log.i("======tv", "getProgress: "+tv);
            wb.setVideoPath(s);
            wb.start();
        }
    }

    @Override
    public void getData(ResponseBody responseBody) {

    }
}




你可能感兴趣的:(多线程)