Android 中获取网络下载速率的方法

Android 中获取网络下载速率的方法,第1张

文章目录

  • 相关方法如下:
// 获取应用程序的 uid
public static int getAppUid() {
    int uid = -1;
    // KmApplication是我的自定义Application,同学们自己根据demo是啥做对应修改即可
    PackageManager packageManager = KmApplication.getContext().getPackageManager();
    try {
      ApplicationInfo applicationInfo =
              packageManager.getApplicationInfo(BuildConfig.APPLICATION_ID,
                      PackageManager.GET_META_DATA);
      // The kernel user-ID that has been assigned to this application
      uid = applicationInfo.uid;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return uid;
  }

public static long lastTotalRxBytes;
public static long lastTimeStamp;

/**
   * 获取网络下载速度
   * @param uid
   * @return
   */
  public static int getNetSpeed(int uid) {
    long nowTotalRxBytes = getTotalRxBytes(uid);
    long nowTimeStamp = System.currentTimeMillis();
    long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换

    lastTimeStamp = nowTimeStamp;
    lastTotalRxBytes = nowTotalRxBytes;

    int result = 0;
    try {
      result = (int) speed;
    } catch (Exception e) {}
    return result;
  }

// Return number of bytes received by the given UID since device boot.
public static long getTotalRxBytes(int uid) {
    //转为KB
    return TrafficStats.getUidRxBytes(uid)==TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes()/1024);
  }

/**
   * 下载速度字符串格式化
   *
   * @param speed
   * @return
   */
  public static String speedFormat(int speed) {
    String result;
    if (speed > 1024) {
      int partA = speed / 1024;
      int partB = (speed - partA * 1024) / 100;
      result = partA + "." + partB + "m/s";
    } else {
      result = speed + "kb/s";
    }
    return result;
  }

可以将上面方法放到工具类里。


  • 使用如下:

// 在需要获取下载速率的地方调用api获取
speedFormat(getNetSpeed(getAppUid()))


技术永不眠!我们下期见!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/733320.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存