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

断了今生、忘了曾经 提交于 2019-12-07 05:49:35

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/26031295/android-how-to-know-internet-total-data-usage-per-day-through-wifi-and-mobile

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