网络框架之可断点续下载

package com.looklook.xinghongfei.looklook.zhou;

import android.os.AsyncTask;
import android.os.Environment;
import android.webkit.DownloadListener;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 6418000420 on 2017/3/2.
 */

public class DownLoadTask extends AsyncTask<String , Integer, Integer>{

    public static final int FAIL = 1;
    public static final int SUCCESS = 0;
    public static final int CANCELED = 2;
    public static final int PAUSE = 3;
    private DownLoadListener mListener;
    private boolean isPaused = false;
    private boolean isCancelled = false;
    private int lastProgress = 0;

    public DownLoadTask(DownLoadListener listener) {
        this.mListener = listener;
    }
    
    @Override
    protected Integer doInBackground(String... strings) {
        InputStream in = null;
        RandomAccessFile savedfile = null;
        File file = null;
        try {
            long downloadlength = 0;
            String downloadurl = strings[0];
            String filename = downloadurl.substring(downloadurl.lastIndexOf("/"));
            String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
            file = new File(directory+filename);
            if (file.exists())
            {
                downloadlength = file.length();
            }
            long contentlength = getContentlength(downloadurl);
            if (contentlength == 0)
            {
                return FAIL;
            }else if (contentlength == downloadlength)
            {
                return SUCCESS;
            }
            OkHttpClient okclient = new OkHttpClient();
            Request request = new Request.Builder()
                    .addHeader("Range","bytes="+downloadlength+"-")
                    .url(downloadurl)
                    .build();
            Response response = okclient.newCall(request).execute();
            if (response != null)
            {
                in = response.body().byteStream();
                savedfile = new RandomAccessFile(file,"rw");
                savedfile.seek(downloadlength);
                byte[] b = new byte[1024];
                int total = 0;
                int len ;
                while ((len = in.read(b))!= -1)
                {
                    
                    if (isCancelled){
                        return CANCELED;
                    }else if (isPaused)
                    {
                        return PAUSE;
                    }else {
                        total += len;
                        savedfile.write(b,0,len);
                        int progress = (int) ((total + downloadlength) * 100/contentlength); 
                        publishProgress(progress);
                    }
                }
                response.body().close();
                return SUCCESS;
            }
            
            
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (in != null)
                {
                    in.close();
                }
                if (savedfile != null)
                {
                    savedfile.close();
                }
                if (isCancelled && file != null)
                {
                    file.delete();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return FAIL;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        int progress = values[0];
        if (progress > lastProgress)
        {
            mListener.Progress(progress);
        }
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }


    private long getContentlength(String downloadurl) throws Exception {
        OkHttpClient okclient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(downloadurl)
                .build();
        Response response = okclient.newCall(request).execute();
        if (response != null && response.isSuccessful())
        {
            long contentleng = response.body().contentLength();
            return contentleng;
        }
        return 0;
    }

    @Override
    protected void onPostExecute(Integer integer) {
        switch (integer){
            case SUCCESS:
                mListener.onSuccess();
            break;
            case FAIL:
                mListener.onFail();
            break;
            case PAUSE:
                mListener.onPaused();
            break;
            case CANCELED:
                mListener.onCanceled();
            break;
        }
    }


    public void Pausedownload() {
       isPaused = true;
    }

    public void canceldownload() {
       isCancelled = true;
    }
}

###对应的接口

package com.looklook.xinghongfei.looklook.zhou;

/**
 * Created by 6418000420 on 2017/3/2.
 */

public interface DownLoadListener {
    
    void onSuccess();
    
    void onFail();
    
    void Progress(int i);
    
    void onPaused();
    
    void onCanceled();
        
}

转载于:https://my.oschina.net/u/3292760/blog/849686

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值