package com.ydl.ydlcommon.utils;

import android.content.Context;
import android.net.TrafficStats;

/**
 * @author jiucheng
 * @描述:网速测量----当前总流量➗（结束时间-开始时间）
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/10/12
 */

public class NetWorkSpeedUtils {
    private Context context;

    /**
     * 开始时下载总流量(按业务需求：只统计了下载网速，不统计上行网速)
     */
    private long startTotalRxBytes = 0;
    /**
     * 开始时间
     */
    private long startTimeStamp = 0;

    public NetWorkSpeedUtils(Context context) {
        this.context = context;
    }

    /**
     * 开始统计
     */
    public void startNetSpeed() {
        startTotalRxBytes = getTotalRxBytes();
        startTimeStamp = System.currentTimeMillis();
    }


    private long getTotalRxBytes() {
        return TrafficStats.getUidRxBytes(context.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ?
                0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
    }

    /**
     * 获取网速
     *
     * @return
     */
    public String getNetSpeed() {
        long endTotalRxBytes = getTotalRxBytes();
        long endTimeStamp = System.currentTimeMillis();
        long speed = (endTotalRxBytes - startTotalRxBytes) * 1000 / (endTimeStamp - startTimeStamp);
        long speed2 = ((endTotalRxBytes - startTotalRxBytes) * 1000 % (endTimeStamp - startTimeStamp));

        return speed + "." + speed2 + "kb/s";
    }
}
