如何使用TrafficStats类在Android中获取Wifi数据计数器

时间:2013-08-07 09:08:43

标签: android networking

我使用以下代码在Android中使用“TrafficStats”类

获取流量数据
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);
}

main.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"/>

它返回的值是Mobile(我认为是所有网络的组合)。有没有办法获得单独的Wi-Fi和3G价值?我也注意到歧视有很多准确性问题。

1 个答案:

答案 0 :(得分:1)

        TextView totData = (TextView)findViewById(R.id.totData);

        TextView wifiTot = (TextView)findViewById(R.id.wifitotData);
        TextView wifiTX = (TextView)findViewById(R.id.wifiUpData);
        TextView wifiRX = (TextView)findViewById(R.id.wifiDownData);

        TextView mobileTot = (TextView)findViewById(R.id.mobtotData);
        TextView mobTX = (TextView)findViewById(R.id.mobUpData);
        TextView mobRX = (TextView)findViewById(R.id.mobDownData);

        /*
         * Converting bytes to MB
         */
        long rxBytes = TrafficStats.getTotalRxBytes()/1048576;
        long txBytes = TrafficStats.getTotalTxBytes()/1048576;

        long mobUpload = TrafficStats.getMobileTxBytes()/1048576;
        long mobDown = TrafficStats.getMobileRxBytes()/1048576;

        long wifiUpload = txBytes-(mobUpload);
        long wifiDown = rxBytes-(mobDown);

        wifiRX.setText(Long.toString(wifiDown));
        wifiTX.setText(Long.toString(wifiUpload));
        long wifitot = wifiUpload+wifiDown;
        wifiTot.setText(Long.toString(wifitot));

        mobTX.setText(Long.toString(mobUpload));
        mobRX.setText(Long.toString(mobDown));
        long mobTot = mobUpload+mobDown;
        mobileTot.setText(Long.toString(mobTot));

        totData.setText(Long.toString(wifitot+mobTot));