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

1

5

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.

Mayfly answered 25/9, 2014 at 5:34 Comment(0)
K
7

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:

  • use the methods provided by the TrafficStats class to get the total number of internet usage
  • subtract mobile data from total to get only the WiFi usage
  • convert bytes to whatever unit you want by using a conversion ratio
  • store the amount of usage at the beginning of a day, and then subtract the amount of usage at the end of the day to get the amount used for that day
Kathlenekathlin answered 25/9, 2014 at 5:54 Comment(4)
are you using alarm manger or intent service to capture data whole day even if the app is not in foreground,Angel
I would imagine this type of app would run 24/7 in the background.Kathlenekathlin
TrafficStats will clear all data usage when Device reboot, just noted it, if you want to use it.Cichocki
If the mobile data is off, then TrafficStats returns getMobileRxBytes, getMobileTxBytes as 0. Is there any best solution for this?Archangel

© 2022 - 2024 — McMap. All rights reserved.