美文网首页
Android 实现下载限速跟下载网速统计

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

作者: 小于先森 | 来源:发表于2020-07-24 17:05 被阅读0次

    引言

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

    代码

    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());
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Android 实现下载限速跟下载网速统计

          本文链接:https://www.haomeiwen.com/subject/mrpnhktx.html