Android application traffic info

Android platform offers data about the installed applications. One of the most interesting one is the application data usage, i.e. how much traffic has the application generated.

Android platform offers this information through TrafficStats class. This class offers the data either as packet count or as transferred bytes. The following example shows how to get the data and show it.

Prerequisite

To get the most out of this tutorial, you’ll need only basic knowledge of Android development. The example code uses as button to refresh the data, so if click handling is not familiar concept, then I suggest first to read my tutorial about that.

Example

package com.caphal.android.trafficstats;

import android.app.Activity;
import android.net.TrafficStats;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class TrafficStatsActivity extends Activity {

    private TextView mobileRxBytes;
    private TextView mobileRxPackets;

    private TextView totalRxBytes;
    private TextView totalRxPackets;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_traffic_stats);

        mobileRxBytes = (TextView) findViewById(R.id.mobile_rx_bytes);
        mobileRxPackets = (TextView) findViewById(R.id.mobile_rx_packets);

        totalRxBytes = (TextView) findViewById(R.id.total_rx_bytes);
        totalRxPackets = (TextView) findViewById(R.id.total_rx_packets);

        refreshTrafficStats();
    }

    /**
     * Update traffic stats
     */
    private void refreshTrafficStats() {

        mobileRxBytes.setText(TrafficStats.getMobileRxBytes() + "");
        mobileRxPackets.setText(TrafficStats.getMobileRxPackets() + "");

        totalRxBytes.setText(TrafficStats.getTotalRxBytes() + "");
        totalRxPackets.setText(TrafficStats.getTotalRxPackets() + "");
    }

    public void onRefreshClick(View view) {
        refreshTrafficStats();
    }
}

In the code above, refreshTrafficStats method reads the traffic information and updates the TextViews. Also if the user presses the Refresh button, the onRefreshClick is called and the traffic data is re-read and updated to the screen.

The example uses only few methods of the TrafficStats class. Checkout the JavaDoc for all available methods.

Screenshots

Initial traffic stats Updated traffic stats

Source code

Source code for this example project is available here

Further reading

Comments

comments powered by Disqus