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

眉间皱痕 提交于 2019-12-05 10:30:51

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!