How to get trafficstats from a specific thread

3.3k Views Asked by At

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.

1

There are 1 best solutions below

1
On

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.