Search code examples
androidnetwork-programmingiptablesnetfilter

How does Android tracks data usage per application?


Android can track how may bytes were send and received from/to application.
I want to know how this data is counted. For example when I run native application, open the TCP socket, send and receive data, this data is accounted.
I know it has something to do with xt_qtaguid module, that tags sockets per UID.


Solution

  • Quick hunt:

    From a quick look in packages/apps/Settings (http://androidxref.com/5.1.1_r6/xref/packages/apps/Settings/src/com/android/settings/DataUsageSummary.java#296) it seems it relies on the

    NetworkStatsService: http://androidxref.com/5.1.1_r6/xref/frameworks/base/services/core/java/com/android/server/net/NetworkStatsService.java#906

    Which seems to boil down to reading from:

    mStatsXtIfaceAll = new File(procRoot, "net/xt_qtaguid/iface_stat_all");
    mStatsXtIfaceFmt = new File(procRoot, "net/xt_qtaguid/iface_stat_fmt");
    mStatsXtUid = new File(procRoot, "net/xt_qtaguid/stats");
    

    "net/xt_qtaguid/stats" seems to contain information on app level.

    -- Skipping a few steps here, but after this file is only opened for reading, it's written by the xt_qtaguid kernel module.

    Code for that: https://android.googlesource.com/kernel/common/+/f0cfc3cc16a15c41107e83f49b61fe2e5a5303be/net/netfilter/xt_qtaguid.c

    Kernel is not my expertise, and we're outside of the "Android" part of the System now, perhaps this question belongs as a Linux Kernel question instead of an Android question? :)