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.
Asked
Active
Viewed 2,714 times
1 Answers
3
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.

Gustavo Morales
- 2,614
- 9
- 29
- 37
-
1But is it then possible to use TrafficStats to give you the bytes transferred only for traffic tagged with that tag? There may be multiple network operations happening in the app at the same time... how to get Rx or Tx bytes only for a particular tag, e.g. for a specific network-related task and not anything else? The only method I see is getTotalRxBytes()... no possibility to filter on a specific tag? – drmrbrewer Aug 12 '17 at 10:19