[Android开发] 使用okhttp下载文件(带监听)

DownloadManager.java

package com.minstone.mdoctor.tool.net;

import android.os.Handler;
import android.os.Looper;

import com.minstone.util.LogUtil;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

import static com.minstone.util.FileAccessor.getFileName;

/**
 * Created by LITP on 2016/9/26.
 */

public class DownloadManager {


    public DownloadManager() {
        mDelivery = new Handler(Looper.getMainLooper());
    }

    private Handler mDelivery;     //主线程返回

    private Call downCall;         //下载的call

    private static OkHttpClient mOkHttpClient;

    private static DownloadManager mInstance;    //单例

    public static DownloadManager getInstance() {
        if (mInstance == null) {
            synchronized (OkHttpManager.class) {
                if (mInstance == null) {
                    mInstance = new DownloadManager();
                }
            }
        }
        return mInstance;
    }



    //synchronized修饰的静态方法锁定的是这个类的所有对象,保证在同一时刻最多只有一个线程执行该段代码
    public synchronized  OkHttpClient getOkHttpClient() {
        if (null == mOkHttpClient) {
            try {
                mOkHttpClient = newOkHttpClient();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mOkHttpClient;
    }

    /**
     * 创建okhttp
     *
     * @return
     * @throws Exception
     */
    private OkHttpClient newOkHttpClient() throws Exception {

        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient();

        TrustManager tm = new OkHttpManager.myTrustManager();
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[]{tm}, null);

        mOkHttpClient.setSslSocketFactory(sslContext.getSocketFactory());


        return mOkHttpClient;
    }


    /**
     * 异步下载文件
     *
     * @param url         文件的下载地址
     * @param destFileDir 本地文件存储的文件夹
     * @param callback
     */
    private void okHttpDownload(final String url, final String destFileDir, final ResultCallback callback) {

        final Request request = new Request.Builder()
                .url(url)
                .build();

        downCall = getOkHttpClient().newCall(request);
        downCall.enqueue(new Callback() {
            @Override
            public void onFailure(final Request request, final IOException e) {
                sendFailedStringCallback(request, e, callback);
            }

            @Override
            public void onResponse(Response response) {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    double current = 0;
                    double total = response.body().contentLength();

                    is = response.body().byteStream();
                    File file = new File(destFileDir, getFileName(url));
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        current += len;
                        fos.write(buf, 0, len);
                        LogUtil.w("download current------>" + current);
                        sendProgressCallBack(total, current, callback);
                    }
                    fos.flush();
                    //如果下载文件成功,第一个参数为文件的绝对路径
                    sendSuccessResultCallback(file.getAbsolutePath(), callback);
                } catch (IOException e) {
                    sendFailedStringCallback(response.request(), e, callback);
                } finally {
                    try {
                        if (is != null) is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        if (fos != null) fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        });
    }

    //下载失败ui线程回调
    private void sendFailedStringCallback(final Request request, final Exception e, final ResultCallback callback) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null)
                    callback.onError(request, e);
            }
        });
    }

    //下载成功ui线程回调
    private void sendSuccessResultCallback(final Object object, final ResultCallback callback) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onResponse(object);
                }
            }
        });
    }


    //下载回调接口
    public static abstract class ResultCallback<T> {

        //下载错误
        public abstract void onError(Request request, Exception e);

        //下载成功
        public abstract void onResponse(T response);

        //下载进度
        public abstract void onProgress(double total, double current);
    }


    /**
     * 进度信息ui线程回调
     *
     * @param total    总计大小
     * @param current  当前进度
     * @param callBack
     * @param <T>
     */
    private <T> void sendProgressCallBack(final double total, final double current, final ResultCallback<T> callBack) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null) {
                    callBack.onProgress(total, current);
                }
            }
        });
    }


    /*  下面为对外开放接口 */




    /**
     * 下载文件
     *
     * @param url 文件链接
     * @param destDir 下载保存地址
     * @param callback 回调
     */
    public static void downloadFile(String url, String destDir, ResultCallback callback) {
        getInstance().okHttpDownload(url, destDir, callback);
    }


    /**
     * 取消下载
     */
    public static void cancleDown(){
        getInstance().downCall.cancel();
    }





}

使用:


    private void startDown(){
        String apkUrl = "apk下载的链接";
        String fileUrl = Environment.getExternalStorageDirectory().getAbsolutePath();
        DownloadManager.downloadFile(apkUrl,fileUrl,new DownloadCallBack());
    }


    //监听类
    class DownloadCallBack extends DownloadManager.ResultCallback {

        @Override
        public void onError(Request request, Exception e) {
            //下载失败返回
        }

        @Override
        public void onResponse(Object response) {
            //下载成功返回
        }

        @Override
        public void onProgress(double total, double current) {
            //进度返回
        }
    }




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KeepStudya

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值