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> S createService(Class<S> serviceClass) {
        Retrofit retrofit = builder.client(httpClient.build()).build();
        return retrofit.create(serviceClass);
    }
}

API:

public interface RetrofitAPI {
    @Streaming
    @GET
    Observable<ResponseBody> 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<ResponseBody>() {
                    @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<ResponseBody>() {
                        @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<IDownLoadView> {

    SoftReference<IDownLoadView> 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<IDownLoadView>(view);
    }

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

Activity:

public class DownLoadActivity extends BaseActivity<DownLoadPresenter> 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) {

    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值