方法定义
import android.net.TrafficStats;
import android.os.SystemClock;
public class NetworkSpeedUtil {
private static long lastTime = 0L;
private static long lastRxBytes = 0L;
private static long lastTxBytes = 0L;
/**
* 获取实时的下行网速(接收速度)
*
* @return 返回下行网速(单位:Mbps)
*/
public static double getRxSpeed() {
long currentTime = SystemClock.elapsedRealtime();
long currentRxBytes = TrafficStats.getTotalRxBytes();
if (lastTime > 0) {
long timeDelta = currentTime - lastTime;
long rxBytesDelta = currentRxBytes - lastRxBytes;
double speed = (rxBytesDelta * 8) / (timeDelta * 1000.0); // 转换为Mbps
return speed;
} else {
lastTime = currentTime;
lastRxBytes = currentRxBytes;
return 0.0;
}
}
/**
* 获取实时的上行网速(发送速度)
*
* @return 返回上行网速(单位:Mbps)
*/
public static double getTxSpeed() {
long currentTime = SystemClock.elapsedRealtime();
long currentTxBytes = TrafficStats.getTotalTxBytes();
if (lastTime > 0) {
long timeDelta = currentTime - lastTime;
long txBytesDelta = currentTxBytes - lastTxBytes;
double speed = (txBytesDelta * 8) / (timeDelta * 1000.0); // 转换为Mbps
return speed;
} else {
lastTime = currentTime;
lastTxBytes = currentTxBytes;
return 0.0;
}
}
}