开发中经常遇到需要显示实时网速的需求,方法很多,这里贴一个我用过的方法,代码不多,拿来就能用
package com.a4kgarden.mynetspeed;
import android.content.Context;
import android.net.TrafficStats;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
private long rxtxTotal = 0;
private long mobileRecvSum = 0;
private long mobileSendSum = 0;
private long wlanRecvSum = 0;
private long wlanSendSum = 0;
private DecimalFormat showFloatFormat = new DecimalFormat("0.00");
private TextView tvspeed;
private Timer timer;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvspeed = (TextView) findViewById(R.id.tvspeed);
timer = new Timer();
timer.scheduleAtFixedRate(new RefreshTask(), 0L, (long) 2000d);
}
public void updateViewData(Context context) {
long tempSum = TrafficStats.getTotalRxBytes()
+ TrafficStats.getTotalTxBytes();
long rxtxLast = tempSum - rxtxTotal;
double totalSpeed = rxtxLast * 1000 / 2000d;
rxtxTotal = tempSum;
tvspeed.setText(showSpeed(totalSpeed));
}
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;
}
class RefreshTask extends TimerTask {
@Override
public void run() {
// 当前有悬浮窗显示,则更新内存数据。
rxtxTotal = TrafficStats.getTotalRxBytes()
+ TrafficStats.getTotalTxBytes();
handler.post(new Runnable() {
@Override
public void run() {
updateViewData(getApplicationContext());
}
});
}
}
}