Android application traffic info

Updated in Android

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.tanelikorri.android.trafficstats;

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

import androidx.appcompat.app.AppCompatActivity;

public class TrafficStatsActivity extends AppCompatActivity {

    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 = findViewById(R.id.mobile_rx_bytes);
        mobileRxPackets = findViewById(R.id.mobile_rx_packets);

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

        refreshTrafficStats();
    }

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

        mobileRxBytes.setText(String.valueOf(TrafficStats.getMobileRxBytes()));
        mobileRxPackets.setText(String.valueOf(TrafficStats.getMobileRxPackets()));

        totalRxBytes.setText(String.valueOf(TrafficStats.getTotalRxBytes()));
        totalRxPackets.setText(String.valueOf(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