OkHttp大文件下载

原创 2017年01月03日 22:07:48

系统自带的DownloadManager下载

        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        mReceiver = new Receiver();
        registerReceiver(mReceiver, filter);
    //系统提供的DownloadManager来下载
    private void startDownload() {
        final DownloadManager downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DOWNLOAD_URL));
        request.setDestinationInExternalFilesDir(this, null, "yixin.apk");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setMimeType("application/vnd.android.package-archive");
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);

        mDownloadId = downloadManager.enqueue(request);
    }
    public class Receiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (mDownloadId == reference) {
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(reference);

                Cursor cursor = ((DownloadManager)(getSystemService(
                        Context.DOWNLOAD_SERVICE))).query(query);
                if (cursor.moveToFirst()) {
                    String fileName = cursor.getString(cursor.getColumnIndex(
                            DownloadManager.COLUMN_LOCAL_FILENAME));
                    mTvResult.setText(fileName);
                }
                cursor.close();
            }
        }
    }

使用OkHttp下载

分片下载
    获取文件大小
    分片下载数据
    是否完成
    //OkHttpClient配置
    private OkHttpClient getClient() {
        if (null == mHttpClient) {
            mHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS).build();
        }
        return mHttpClient;
    }
   private static final String DOWNLOAD_URL = "http://yixin.dl.126.net/update/installer/yixin.apk";

    private Button mBtnDownloadSelf;
    private ProgressBar mProgressBar;

    private OkHttpClient mHttpClient;

    private DownloadState mState = DownloadState.PENDING;

    private int mTotal;

    private static final int DELTA = 256 * 1024;

    private OutputStream mDstOutputStream;

    private int mCurrentDownload;

    private enum DownloadState {
        PENDING,
        DOWNLOADING,
        PAUSE,
        DONE
    }
   @Override
    public void onClick(View v) {
        if (R.id.btn_download_by_system == v.getId()) {
//            startDownload();
        } else if (R.id.btn_download_self == v.getId()) {
            switch (mState) {
                case PENDING:
                    startDownloadSelf();
                    mState = DownloadState.DOWNLOADING;
                    break;
                case DOWNLOADING:
                    mState = DownloadState.PAUSE;
                    break;
                case PAUSE:
                    mState = DownloadState.DOWNLOADING;
                    downloadRange(mCurrentDownload);
                    break;
            }
            refreshButton();
        }
    }
    private void refreshButton() {
        switch (mState) {
            case DOWNLOADING:
                mBtnDownloadSelf.setText(R.string.pause);
                break;
            case PENDING:
                mBtnDownloadSelf.setText(R.string.start_download);
                break;
            case PAUSE:
                mBtnDownloadSelf.setText(R.string.resume);
                break;
            case DONE:
                mBtnDownloadSelf.setText(R.string.done);
                break;
        }
    }
    //开始下载
    private void startDownloadSelf() {
        getFileLength(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    //获取下载文件长度
                    mTotal = Integer.valueOf(response.header("Content-Length"));
                    mDstOutputStream = new FileOutputStream(getExternalFilesDir(null).getAbsolutePath() + "/yixin.apk");
                    downloadRange(0);
                }
            }
        });
    }

    //获取文件大小
    private void getFileLength(Callback callback) {
        Request request = new Request.Builder()
                .url(DOWNLOAD_URL)
                .method("HEAD", null).build();

        getClient().newCall(request).enqueue(callback);
    }

    private void downloadRange(int start) {
        //分段下载,range参数将文件进行分片
        Request request = new Request.Builder()
                .url(DOWNLOAD_URL)
                .addHeader("range", "bytes=" + start + "-" + Math.min(start + DELTA, mTotal)).build();

        getClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful() && mState == DownloadState.DOWNLOADING) {
                    final byte[] bytes = response.body().bytes();
                    mDstOutputStream.write(bytes);
                    mCurrentDownload += bytes.length;
                    mProgressBar.post(new Runnable() {
                        @Override
                        public void run() {
                            int progress = (int)(mCurrentDownload * 1.0 / mTotal * 100);
                            mProgressBar.setProgress(progress);

                            if (100 == progress) {
                                mState = DownloadState.DONE;
                                refreshButton();
                            }
                        }
                    });

                    if (mCurrentDownload >= mTotal) {
                        mDstOutputStream.flush();
                        mDstOutputStream.close();
                        return;
                    }

                    downloadRange(mCurrentDownload);
                }
            }
        });
    }
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Android中的主题样式

Android资源打包,Android主题样式,style,theme,定义style,继承已有的style,style应用,常用的Theme,style版本兼容,support中对应的主题(已做版本...

Android OkHttp完全解析 是时候来了解OkHttp了

转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/47911083; 本文出自:【张鸿洋的博客】 一、概述 最...

OkHttp 官方中文文档

OkHttp文档本文结构 Calls Connections Recipes Interceptors HTTPS 本文翻译来自 官方OkHttp Wiki OkHttp文档 一Calls 1 请求...

Android okHttp 实战(二):okHttp网络请求之文件上传下载

原文地址:http://www.cnblogs.com/whoislcj/p/5529827.html  前面介绍了基于okHttp的get、post基本使用(http://www.cnblogs....

类似微信的文本输入框

本文内容比较简单,给大家介绍一下微信的文本输入框是如何实现的,其实那只是个普通的文本框设了一个特殊的背景而已。具体微信怎么实现的,大家可以反编译下,这里介绍下如何实现这个背景。可以先看下文章末尾的效果...

OKHttp实现大文件的断点续传

本文的亮点: (1)网络请求用OKHttp进行下载大文件 (2)实现了大文件的断点续传 (3)取消下载时,删除已经下载的文件。 实现效果图:          直接给出工程: (1)定义一个接口:D...

OkHttp官方教程解析-彻底入门OkHttp使用

最近半年来身边开发的朋友越来越多的提到OkHttp,上谷歌百度一下,确实OkHttp成了时下最火的HTTP框架,于是我也开始放下Volley,转而关注OkHttp,五一期间仔细看了官方WiKi介绍(我...

使用Okhttp网络请求下载图片到指定文件夹

一.在module中添加依赖    compile 'com.squareup.okhttp3:okhttp:3.6.0'   二.设置布局  xml version=".....
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)