TrafficStats Api android and calculation of daily data usage

Naba picture Naba · Oct 3, 2011 · Viewed 13.7k times · Source

Have a confusion over following two methods of TrafficStats of Android: getUidTxBytes(int uid) and getUidRxBytes(int uid) , These two methods return the number of bytes transmitted and received through the network for this UID. But what is the time unit of it, is it per second? If I want to calculate data transmitted and received per day per app, what should I do. I thought one way, to store data in sql and keep on adding data to the table. Is it proper way?

Answer

haimg picture haimg · Oct 3, 2011

These are counters "since the interface went up" or "since the application with this UID has started". So say if your phone goes into "Airplane mode" and then back, the counters might start from zero again. If you need per-second values, you'll need to call these functions every second, and then use the delta from the last call. If the delta is negative, just use the value as-is, it means the counter started from zero again.

One more thing: As far as I know, these counters count TCP/IP only. Not UDP. So if you need a very precise accounting, and the application in question uses UDP/IP, or any other protocol besides TCP, these counters will be wrong.

For the insight how this function works, look at the source of Android, freely available. File in question is ./frameworks/base/core/jni/android_net_TrafficStats.cpp

This function gets the data from /proc/uid_stat/[uid]/tcp_snd. If you need more info about that, you'll need to dive into the Linux kernel...