简单实现断点续传+MVP+Retrofit+RxJava

依赖:

compile 'com.squareup.retrofit2:retrofit:2.0.1'
    compile 'com.squareup.retrofit2:converter-gson:2.0.1'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1'
    compile 'io.reactivex:rxandroid:1.1.0'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    compile 'com.android.support:mediarouter-v7:25.0.0'
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support:recyclerview-v7:25.0.0'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.facebook.fresco:fresco:0.11.0'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'com.jcodecraeer:xrecyclerview:1.3.2'

Api类

public class Api {
    public static final String Urljson1 = "https://api.tianapi.com/wxnew/";
}

ApiService类


public interface ApiService {
    @POST
    Observable getUser(@Url String url);
}

IModel类

public interface IModel {
    void getJson(String url);
}

UserModel类

import android.util.Log;

import com.six.zhouerlianxi.Apiservers.ApiService;
import com.six.zhouerlianxi.bean.Users;

import java.util.ArrayList;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by wangjiao on 2017/11/11.
 */

public class UserModel implements IModel{
    ArrayList list;

    //刷新加载
    String path;

    public UserModel(String path) {
        this.path = path;
    }

    private OnFinish onFinish;

    public interface OnFinish{
        void OnFinishListener(ArrayList list);
    }

    public void setOnFinish(OnFinish finish){
        this.onFinish=finish;
    }



    @Override
    public void getJson(String url) {
        list = new ArrayList<>();
        Retrofit retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();

        ApiService apiService = retrofit.create(ApiService.class);
        //加载
        final Observable home = apiService.getUser(path);
        home.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Users homeBean) {
                        list = (ArrayList) homeBean.getNewslist();
                        Log.d("1111111111",list.get(0).getTitle());
                        onFinish.OnFinishListener(list);

                    }
                });

    }
}

IView类


public interface IView {
    void getUser(ArrayList list);
}

UserPresenter类


import com.six.zhouerlianxi.bean.Users;
import com.six.zhouerlianxi.model.UserModel;
import com.six.zhouerlianxi.view.IView;

import java.util.ArrayList;

/**
 * Created by wangjiao on 2017/11/11.
 */

public class UserPresenter implements UserModel.OnFinish{
    private final IView userView;
    private final UserModel userModel;
    //加载string url
    public UserPresenter(IView userView,String url) {
        this.userView = userView;
        this.userModel = new UserModel(url);
        userModel.setOnFinish(this);
    }

    public void setNews(String url){
        userModel.getJson(url);
    }

    @Override
    public void OnFinishListener(ArrayList list) {
        userView.getUser(list);
    }
}

MainActivity类

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.loopj.android.http.HttpGet;
import com.six.zhouerlianxi.API.Api;
import com.six.zhouerlianxi.adapter.HomeAdapter;
import com.six.zhouerlianxi.adapter.OnItemClickLitener;
import com.six.zhouerlianxi.bean.Users;
import com.six.zhouerlianxi.presenters.UserPresenter;
import com.six.zhouerlianxi.view.IView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpHead;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;

public class MainActivity extends AppCompatActivity implements IView {
    UserPresenter userPresenter;
    private HomeAdapter adapter;
    private XRecyclerView xr;
    LinearLayout line1;
    protected static final String TAG = "OtherActivity";
    //下载线程的数量
    private final static int threadsize = 3;

    protected static final int SET_MAX = 0;
    public static final int UPDATE_VIEW = 1;

    private boolean flag = false;//是否在下载
    private ProgressBar pb;
    private TextView tv_info;
    //加载
    String url;
    int a=1;
    private ArrayList newslistBeen;
    String uri = "https://zxpic.gtimg.com/infonew/0/wechat_pics_-58717788.jpg/640";
    //显示进度和更新进度
    private Handler mHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case SET_MAX://设置进度条的最大值
                    int filelength = msg.arg1;
                    pb.setMax(filelength);
                    break;
                case UPDATE_VIEW://更新进度条  和 下载的比率
                    int len = msg.arg1;//新下载的长度
                    pb.setProgress(pb.getProgress()+len);//设置进度条的刻度

                    int max = pb.getMax();//获取进度的最大值
                    int progress = pb.getProgress();//获取已经下载的数据量
                    //  下载:30    总:100
                    int result = (progress*100)/max;

                    tv_info.setText("下载:"+result+"%");
                    if (result==100){
                        line1.setVisibility(View.GONE);
                    }
                    break;

                default:
                    break;
            }
        };
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //加载
        newslistBeen = new ArrayList();
        url= "?key=8d6e3228d25298f13af4fc40ce6c9679&num=20&page="+a;


        xr = (XRecyclerView) findViewById(R.id.xre_xrv);
        pb = (ProgressBar) findViewById(R.id.progressBar);
        line1 = (LinearLayout) findViewById(R.id.line1);
        tv_info = (TextView) findViewById(R.id.text3);
        userPresenter = new UserPresenter(this,url);
        userPresenter.setNews(Api.Urljson1);
        String name = getFileName(uri);
        File file = new File(Environment.getExternalStorageDirectory(), name);
        if (file.exists()){//文件存在回显
            //获取文件的大小
            int filelength = (int) file.length();
            pb.setMax(filelength);
            try {
                //统计原来所有的下载量
                int count = 0;
                //读取下载记录文件
                for (int threadid = 0; threadid < threadsize; threadid++) {
                    //获取原来指定线程的下载记录
                    int existDownloadLength = readDownloadInfo(threadid);
                    count = count + existDownloadLength;
                }
                //设置进度条的刻度
                pb.setProgress(count);

                //计算比率
                int result = (count * 100) / filelength;
                tv_info.setText("下载:" + result + "%");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //暂停
        pb.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                flag = false;
                pb.setEnabled(true);
                pb.setEnabled(false);
                Toast.makeText(MainActivity.this,"暂停",Toast.LENGTH_SHORT).show();
                return false;
            }
        });

    }
    //下载
    public void download(View v){
        line1.setVisibility(View.VISIBLE);

        flag = true; //是在下载
            pb.setEnabled(false);//一点击变成不可点击
            pb.setEnabled(true);//一点击变成可点击
        new Thread(){//子线程
            public void run() {
                try {
                    //获取服务器上文件的大小
                    HttpClient client = new DefaultHttpClient();
                    HttpHead request = new HttpHead(uri);
                    HttpResponse response = client.execute(request);
                    //response  只有响应头  没有响应体
                    if(response.getStatusLine().getStatusCode() == 200){
                        Header[] headers = response.getHeaders("Content-Length");
                        String value = headers[0].getValue();
                        //文件大小
                        int filelength = Integer.parseInt(value);
                        Log.i(TAG, "filelength:"+filelength);

                        //设置进度条的最大值
                        Message msg_setmax = Message.obtain(mHandler, SET_MAX, filelength, 0);
                        msg_setmax.sendToTarget();


                        //处理下载记录文件
                        for(int threadid=0;threadid//对应的下载记录文件
                            File file = new File(Environment.getExternalStorageDirectory(),threadid+".txt");
                            //判断文件是否存在
                            if(!file.exists()){
                                //创建文件
                                file.createNewFile();
                            }
                        }


                        //在sdcard创建和服务器大小一样的文件
                        String name = getFileName(uri);
                        File file = new File(Environment.getExternalStorageDirectory(),name);
                        //随机访问文件
                        RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                        //设置文件的大小
                        raf.setLength(filelength);
                        //关闭
                        raf.close();

                        //计算每条线程的下载量
                        int block = (filelength%threadsize == 0)?(filelength/threadsize):(filelength/threadsize+1);

                        //开启三条线程执行下载
                        for(int threadid=0;threadidnew DownloadThread(threadid, uri, file, block).start();
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            };
        }.start();
    }
    @Override
    public void getUser(ArrayList list) {
        //加载
        if (a==1){
            newslistBeen.clear();
        }
        newslistBeen.addAll(list);

        xr.setLayoutManager(new LinearLayoutManager(this));
        adapter = new HomeAdapter(list,this);
        adapter.setOnItemClickLitener(new OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                uri=newslistBeen.get(position).getPicUrl();
                Toast.makeText(MainActivity.this,uri,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemLongClick(View view, int position) {
                Toast.makeText(MainActivity.this,"长按",Toast.LENGTH_SHORT).show();
            }
        });
        xr.setAdapter(adapter);
        //加载
        xr.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                a=1;
                userPresenter = new UserPresenter(MainActivity.this, url);
                userPresenter.setNews(Api.Urljson1);
                adapter.notifyDataSetChanged();;
                xr.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                a++;
                url="?key=8d6e3228d25298f13af4fc40ce6c9679&num=20&page="+a;
                userPresenter = new UserPresenter(MainActivity.this, url);
                userPresenter.setNews(Api.Urljson1);
                adapter.notifyDataSetChanged();;
                xr.loadMoreComplete();
            }
        });


    }
    //线程下载类
    private class DownloadThread extends Thread{
        private int threadid;//线程的id
        private String uri;//下载的地址
        private File file;//下载文件
        private int block;//下载的块
        private int start;
        private int end;

        public DownloadThread(int threadid, String uri, File file, int block) {
            super();
            this.threadid = threadid;
            this.uri = uri;
            this.file = file;
            this.block = block;
            //计算下载的开始位置和结束位置
            start = threadid * block;
            end = (threadid + 1)*block -1;

            try {
                //读取该条线程原来的下载记录
                int existDownloadLength = readDownloadInfo(threadid);

                //修改下载的开始位置   从新下载
                start = start + existDownloadLength;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }



        //下载   状态码:200是普通的下载      206是分段下载        Range:范围
        @Override
        public void run() {
            super.run();
            try {
                RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                //跳转到起始位置
                raf.seek(start);

                //分段下载
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet(uri);
                request.addHeader("Range", "bytes:"+start+"-"+end);//添加请求头
                HttpResponse response = client.execute(request);
                if(response.getStatusLine().getStatusCode() == 200){
                    InputStream inputStream = response.getEntity().getContent();
                    //把流写入到文件
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while((len = inputStream.read(buffer)) != -1){
                        //如果暂停下载  点击暂停 false 就直接return 点击下载true接着下载
                        if(!flag){
                            return;//标准线程结束
                        }
                        //写数据
                        raf.write(buffer, 0, len);

                        //读取原来下载的数据量 这里读取是为了更新下载记录
                        int existDownloadLength = readDownloadInfo(threadid);//原来下载的数据量

                        //计算最新的下载
                        int newDownloadLength = existDownloadLength + len;

                        //更新下载记录 从新记录最新下载位置
                        updateDownloadInfo(threadid, newDownloadLength);

                        //更新进度条的显示   下载的百分比
                        Message update_msg = Message.obtain(mHandler, UPDATE_VIEW, len, 0);
                        update_msg.sendToTarget();
                        //模拟  看到进度条动的效果
                        SystemClock.sleep(50);
                    }
                    inputStream.close();
                    raf.close();
                    Log.i(TAG, "第"+threadid+"条线程下载完成");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 读取指定线程的下载数据量
     * @param threadid  线程的id
     * @return
     * @throws Exception
     */
    public int readDownloadInfo(int threadid) throws Exception{
        //下载记录文件
        File file = new File(Environment.getExternalStorageDirectory(),threadid+".txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        //读取一行数据
        String content = br.readLine();

        int downlength = 0;
        //如果该文件第一次创建去执行读取操作  文件里面的内容是 null
        if(!TextUtils.isEmpty(content)){
            downlength = Integer.parseInt(content);
        }
        //关闭流
        br.close();
        return downlength;
    }


    /**
     * 更新下载记录
     * @param threadid
     * @param newDownloadLength
     */
    public void updateDownloadInfo(int threadid,int newDownloadLength) throws Exception{
        //下载记录文件
        File file = new File(Environment.getExternalStorageDirectory(),threadid+".txt");
        FileWriter fw = new FileWriter(file);
        fw.write(newDownloadLength+"");
        fw.close();
    }

    /**
     * 获取文件的名称
     * @param uri
     * @return
     */
    private String getFileName(String uri){
        return uri.substring(uri.lastIndexOf("/")+1);
    }

}

HomeAdapter类

import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.six.zhouerlianxi.R;
import com.six.zhouerlianxi.bean.Users;

import java.util.List;

/**
 * Created by wangjiao on 2017/11/11.
 */
public class HomeAdapter extends RecyclerView.Adapter.MyViewHolder>
{
    protected static final String TAG = "OtherActivity";

    //下载线程的数量
    private final static int threadsize = 3;

    protected static final int SET_MAX = 0;
    public static final int UPDATE_VIEW = 1;
    List.NewslistBean> userses;
    Context context;
    private OnItemClickLitener mOnItemClickLitener;

    public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener)
    {
        this.mOnItemClickLitener = mOnItemClickLitener;
    }

    public HomeAdapter(List.NewslistBean> userses, Context context) {
        this.userses = userses;
        this.context = context;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        MyViewHolder holder = new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.item_home, parent, false));
        return holder;
    }


    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position)
    {
        holder.tv.setText(userses.get(position).getTitle());
        Uri uri =  Uri.parse(userses.get(position).getPicUrl());
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setUri(uri)
                .setAutoPlayAnimations(true)
                .build();
        holder.image.setController(controller);
        // 如果设置了回调,则设置点击事件
        if (mOnItemClickLitener != null)
        {
            holder.itemView.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    int pos = holder.getLayoutPosition();
                    mOnItemClickLitener.onItemClick(holder.itemView, pos);

                }
            });

            holder.itemView.setOnLongClickListener(new View.OnLongClickListener()
            {
                @Override
                public boolean onLongClick(View v)
                {
                    int pos = holder.getLayoutPosition();
                    mOnItemClickLitener.onItemLongClick(holder.itemView, pos);
                    return false;
                }
            });
        }

    }

    @Override
    public int getItemCount()
    {
        return userses.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder
    {

        TextView tv;
        SimpleDraweeView image;

        public MyViewHolder(View view)
        {
            super(view);
            tv = view.findViewById(R.id.text);
            image = (SimpleDraweeView) view.findViewById(R.id.image);


        }
    }

}

进度条

你可能感兴趣的:(简单实现断点续传+MVP+Retrofit+RxJava)