androidwifiandroid-data-usagemobile-data

Android how to know Internet total data usage per day through wifi and mobile


How to know internet total data usage per day?

For example, at the end of the day I used 800mb then it should return like "internet usage of 800mb on 20th May 2015".

So how can I detect total data usage ?

After much googling I could only find data usage in sending and receiving bytes but not in total usage.

And also want to split the usage into wifi and mobile data.


Solution

  • Take a look at the TrafficStats class. For this, you'll want to look specifically at getTotalRxBytes(), getTotalTxBytes(), getMobileRxBytes(), and getMobileTxBytes().

    A quick overview:

    getTotalRxBytes = total downloaded bytes
    getTotalTxBytes = total uploaded bytes
    
    getMobileRxBytes = only mobile downloaded bytes
    getMobileTxBytes = only mobile uploaded bytes
    

    So, in order to get only the number for WiFi related traffic, you would only need to get the total, and subtract the mobile, as such:

    getTotalRxBytes - getMobileRxBytes = only WiFi downloaded bytes
    getTotalTxBytes - getMobileTxBytes = only WiFi uploaded bytes
    

    With the number of bytes, we can switch to different units, such as megabytes (MB):

    getTotalRxBytes / 1048576 = total downloaded megabytes
    

    As for getting usage for an interval, for example a day, since these methods only provide the total (since boot), you will need to keep track of the beginning number and then subtract to get the number of bytes used during an interval. So, at the beginning of the day, such as 12:00:00AM, you keep track of the total usage:

    startOfDay = getTotalRxBytes + getTotalTxBytes;
    

    When the end of the day comes, such as 11:59:59PM, you can then subtract the two numbers and get the total usage for that day:

    endOfDay    = getTotalRxBytes + getTotalTxBytes;
    usageForDay = endOfDay - startOfDay;
    

    So a summary: