Android 中获取网络下载速率的方法
Posted 邹奇
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 中获取网络下载速率的方法相关的知识,希望对你有一定的参考价值。
文章目录
- 相关方法如下:
// 获取应用程序的 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()))
技术永不眠!我们下期见!
以上是关于Android 中获取网络下载速率的方法的主要内容,如果未能解决你的问题,请参考以下文章
从 onCameraFrame、OpenCV、Android/Java 调用 HoughCircles() 方法时改变慢帧速率