import android.content.Context;
import android.net.TrafficStats;
import android.os.Handler;
import android.os.Looper;
public class NetworkSpeedMonitor {
private static long lastTotalRxBytes = 0;
private static long lastTime = 0;
public interface SpeedCallback {
void onSpeedCalculated(long speed); // speed in bytes per second
}
public static void startMonitoring(Context context, long intervalMillis, final SpeedCallback callback) {
Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
@Override
public void run() {
long currentTotalRxBytes = TrafficStats.getTotalRxBytes();
long currentTime = System.currentTimeMillis();
if (lastTime != 0) {
// 计算每秒字节数(bytes per second)
long speed = (currentTotalRxBytes - lastTotalRxBytes) * 1000L / (currentTime - lastTime);
callback.onSpeedCalculated(speed);
}
lastTotalRxBytes = currentTotalRxBytes;
lastTime = currentTime;
// 延迟后继续执行
handler.postDelayed(this, intervalMillis);
}
};
handler.post(runnable);
}
}
使用
NetworkSpeedMonitor.startMonitoring(this, 1000, new NetworkSpeedMonitor.SpeedCallback() {
@Override
public void onSpeedCalculated(long speed) {
Log.d("NetworkSpeed", "Download Speed: " + (speed / 1024) + " KB/s");
}
});