我正在使用以下代码使用“TrafficStats”类在 Android 中获取流量数据
public class TrafficStatisticsDemoActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView infoView = (TextView)findViewById(R.id.traffic_info);
String info = "";
info += "Mobile Interface:\n";
info += ("\tReceived: " + TrafficStats.getMobileRxBytes() + " bytes / " + TrafficStats.getMobileRxPackets() + " packets\n");
info += ("\tTransmitted: " + TrafficStats.getMobileTxBytes() + " bytes / " + TrafficStats.getMobileTxPackets() + " packets\n");
info += "All Network Interface:\n";
info += ("\tReceived: " + TrafficStats.getTotalRxBytes() + " bytes / " + TrafficStats.getTotalRxPackets() + " packets\n");
info += ("\tTransmitted: " + TrafficStats.getTotalTxBytes() + " bytes / " + TrafficStats.getTotalTxPackets() + " packets\n");
infoView.setText(info);
}
主要的.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/traffic_info"
android:padding="10dip"/>
它返回的值是针对移动设备的(我相信它是所有网络的组合)。有什么方法可以分别获得 Wi-Fi 和 3G 的价值?我还注意到在区分方面存在很多准确性问题。