1

「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);
}

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

返される値はモバイル用です(すべてのネットワークの組み合わせであると私は信じています)。Wi-Fi と 3G の値を別々に取得する方法はありますか? また、識別には多くの精度の問題があることに気付きました。

4

1 に答える 1

2
        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));
于 2013-09-25T18:34:49.167 に答える