在网上找了好多获取网速的代码,方法都是差不多的,但是我通过以下代码获得的网速都是0,是哪里出问题了呢?
private Timer myTimer;
private long lastTotalRxBytes = 0;
private long lastTimeStamp = 0;
private void showNetSpeed() {
long nowTotalRxBytes = getTotalRxBytes();
long nowTimeStamp = System.currentTimeMillis();
double speed = (nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp);
Log.d("xxx", "showNetSpeed: " + speed);
lastTimeStamp = nowTimeStamp;
lastTotalRxBytes = nowTotalRxBytes;
Message msg = new Message();
msg.what = 100;
msg.obj = showSpeed(speed);
mHandler.sendMessage(msg);
}
private DecimalFormat showFloatFormat = new DecimalFormat("0.00");
private String showSpeed(double speed) {
String speedString;
if (speed >= 1048576d) {
speedString = showFloatFormat.format(speed / 1048576d) + " MB/s";
} else {
speedString = showFloatFormat.format(speed / 1024d) + " KB/s";
}
return speedString;
}
private long getTotalRxBytes() {
return TrafficStats.getUidRxBytes(MainActivity.this.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ?
0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
}
public void start(View view) {
if (myTimer != null) {
myTimer.cancel();
}
myTimer = new Timer();
lastTotalRxBytes = getTotalRxBytes();
lastTimeStamp = System.currentTimeMillis();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
showNetSpeed();
}
}, 1000, 1000);
}
public void stop(View view) {
if (myTimer != null) {
myTimer.cancel();
}
}
主要是这一块获取字节的代码问题,得到的结果都是0,我想请问一下是什么原因造成的?
private long getTotalRxBytes() {
return TrafficStats.getUidRxBytes(MainActivity.this.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ?
0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
}
没事了,,,,模拟器无效。TrafficStats.getUidRxBytes(MainActivity.this.getApplicationInfo().uid) 这个值为-1,代表不支持