通过使用Handler计算每秒的蜂窝数据速率,代码每秒执行一次并计算整体流量,然后它假设从引导后的当前流量启动后减去旧流量以获取当前数据速率每秒。
我面临的问题是当前数据速率值不正确,它总是给我自启动后的总体流量。可能是我做错了什么,我还是初学者用android。下面的代码。
公共类MainActivity扩展了AppCompatActivity {
private double RXOld;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
////////////////////////Code to be executed every second////////////////////////////////////////
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
double overallTraffic = TrafficStats.getMobileRxBytes();
double currentDataRate = overallTraffic - RXOld;
TextView view1 = null;
view1 = (TextView) findViewById(R.id.view1);
view1.setText("Current Data Rate per second= " + currentDataRate);
double RXOld = overallTraffic;
handler.postDelayed(this, 1000);
}
}, 1000 );
}
答案 0 :(得分:1)
整改后的新代码,它将给出每秒当前的数据速率
public class MainActivity extends AppCompatActivity {
final double [] RXOld = new double [1];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
////////////////////////Code to be executed every second////////////////////////////////////////
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
double overallTraffic = TrafficStats.getMobileRxBytes();
double currentDataRate = overallTraffic - RXOld [0];
TextView view1 = null;
view1 = (TextView) findViewById(R.id.view1);
view1.setText("Current Data Rate per second= " + currentDataRate);
RXOld [0] = overallTraffic;
handler.postDelayed(this, 1000);
}
}, 1000 );
答案 1 :(得分:0)
首先,考虑使用Timer,并在开头声明TextView。我认为这段代码应该可行,但我没有测试它:
final TextView view1 = null;
view1 = (TextView) findViewById(R.id.view1);
final double[] oldT = new double[1];
Timer timer1 = new Timer();
TimerTask tt1 = new TimerTask() {
@Override
public void run() {
double overallTraffic = TrafficStats.getMobileRxBytes();
double trafficRate = overallTraffic - oldT[0];
oldT[0] = overallTraffic;
view1.setText("Current Data Rate per second= " + trafficRate);
}
};
timer1.scheduleAtFixedRate(tt1,1000,1000);
注意:如果在TimerTask的run()中使用新变量,则必须将变量声明为final。您可以通过使变量为1个元素的数组('int [] varName = new int [1]'而不是'int varName'),并使用varName [0]而不是varName
来轻松更改其值