Android 实现下载限速跟下载网速统计

引言

没啥想说的,就是有这个需求,就写下
一切皆在代码中。

代码

package com.cyber.longurl;

import android.util.Log;

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

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import static com.cyber.longurl.AppConfig.TAG;

/***
 * 作者 : 于德海
 * 时间 : 2020/7/24 0024 10:45
 * 描述 : 
 */
public class DownLoadUtil {
    public static boolean isStopDown = false;

    public interface Listener {
        void progressUpdate(float progress, int net);

        void downSuccess(String path);

        void downFail(String msg);
    }

    public static void downFile(final String filePath, final String filename, String downUrl, final Listener listener) {
        Request request = new Request.Builder().url(downUrl).build();
        MyApplication.Companion.getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG, "downFail:" + e.getMessage());
                listener.downFail(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i(TAG, "receive stream start down");
                InputStream is = null;
                FileOutputStream fos = null;
                checkFile(filePath, filename);
                File file = new File(filePath, filename);
                byte[] buf = new byte[1024 * 256];//最多一次读取256k数据
                int len = 0;
                try {
                    ResponseBody body = response.body();
                    is = body.byteStream();
                    long total = body.contentLength();
                    fos = new FileOutputStream(file);
                    long lastTime = System.currentTimeMillis();
                    long lastData = 0;
                    int net = 0;
                    long sum = 0;
                    long lastReceiveData = 0;
                    long lastReceiveTime = System.currentTimeMillis();
                    while ((len = is.read(buf)) != -1) {
                        if (isStopDown) {
                            Log.e(TAG, "down is stop activity is destroy");
                            return;
                        }
                        Log.i(TAG, "len====" + len);
                        fos.write(buf, 0, len);
                        sum += len;
                        if (sum - lastReceiveData > 200*1024) {//限制200k
                            long receive_interval = System.currentTimeMillis() - lastReceiveTime;
                            if (receive_interval < 1000) {
                                try {
                                    Thread.sleep(1000 - receive_interval);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            lastReceiveData = sum;
                            lastReceiveTime = System.currentTimeMillis();
                        }
                        int time = (int) (System.currentTimeMillis() - lastTime);
                        if (time >= 500) {//500ms更新一次数据,正常可以跟上边合到一起,但是懒。
                            float progress = sum * 1.0f / total * 100;
                            BigDecimal b = new BigDecimal(progress);
                            progress = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
                            net = (int) (((sum - lastData) / 1024) * 1.0F / time * 1000);
                            lastData = sum;
                            lastTime = System.currentTimeMillis();
                            listener.progressUpdate(progress, net);
                        }
                    }
                    fos.flush();
                    listener.downSuccess(file.getAbsolutePath());
                } catch (IOException e) {
                    e.printStackTrace();
                    listener.downFail(e.getMessage());
                } finally {
                    if (is != null)
                        is.close();
                    if (fos != null)
                        fos.close();
                }

            }
        });
    }

    private static void checkFile(String filePath, String fileName) {
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();

        }
        file = new File(filePath, fileName);
        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            Log.i(TAG, "createFile error:" + e.getMessage());
        }
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

猫的于

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

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

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

打赏作者

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

抵扣说明:

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

余额充值