Jakob Eriksson
Jakob Eriksson

Reputation: 18767

How to get trafficstats from a specific thread

On android, how can I use TrafficStats and TrafficStatsCompat to get the total TX bytes for a specific thread in the current process? The API implies that it's possible but I can't figure it out.

Upvotes: 2

Views: 3737

Answers (1)

Gustavo Morales
Gustavo Morales

Reputation: 2670

From documentation.

To better identify the cause of transfer spikes, the Traffic Stats API allows you to tag the data transfers occurring within a thread using the TrafficStats.setThreadStatsTag() method, followed by manually tagging (and untagging) individual sockets using tagSocket() and untagSocket(). For example:

TrafficStats.setThreadStatsTag(0xF00D);
TrafficStats.tagSocket(outputSocket);
// Transfer data using socket
TrafficStats.untagSocket(outputSocket);

The Apache HttpClient and URLConnection libraries automatically tag sockets based on the current getThreadStatsTag() value. These libraries also tag and untag sockets when recycled through keep-alive pools.

TrafficStats.setThreadStatsTag(0xF00D);
try {
  // Make network request using HttpClient.execute()
} finally {
  TrafficStats.clearThreadStatsTag();
}

Socket tagging is supported in Android 4.0, but real-time stats will only be displayed on devices running Android 4.0.3 or higher.

Upvotes: 3

Related Questions