How to get the GPRS Mobile data usage for 1 month?

若如初见. 提交于 2020-01-23 06:41:26

问题


I have searched a lot about this. Found the same code everywhere which solves the purpose partially. As API documentation says, it reset the counter once the device restarts. Sometimes the counter just resets even without the restart. Below is the code

float totalRxBytes = (float)TrafficStats.getTotalRxBytes()/(float)1048576;  // Received
float totalTxBytes = (float)TrafficStats.getTotalTxBytes()/(float)1048576;  // Sent
float mobRxBytes = (float)TrafficStats.getMobileRxBytes()/(float)1048576;
float mobTxBytes = (float)TrafficStats.getMobileTxBytes()/(float)1048576;
float wifiRxBytes = totalRxBytes - mobRxBytes;
float wifiTxBytes = totalTxBytes - mobTxBytes;  

But I could not figure out any way to have this data from a specific date OR for a month? Please help. Any pointer will be appreciated. Thanks.


回答1:


First of all, TrafficStats.getTotalRxPackets():

Return number of packets received since device boot.

The same is with TrafficStats.getTotalTxPackets()

This class is not helpful for getting month statistics.

I would advise solution working from API 23:

NetworkStatsManager

This class has the possibility to obtain statistics per device or per package. Especially helpful for you would be function:

NetworkStatsManager.querySummaryForDevice()

which expect measuring start time as third parameter and end time as fourth paramter.

The sample project can be found here. It shows how to obtain access to NetworkStatsManager asking for appropriate runtime permissions.

This solution is only API 23+.

If you really want to use TrafficStats then create a Service that would get the result of TrafficStats.getTotalRxPackets() every hour, count the difference, save it in database in different row per day.




回答2:


I agree with R. Zagorski, but I have a different approach in mind.

Use TrafficStats to get amount of packets received/sent, subtract the last amount from it and then save it using SharedPreferences along with the last amount. Now, to handle a device restart, always check if the last count is greater than current amount. If yes, reset the last amount to 0. Also, keep track of when the month started. As soon the month has ended, don't forget to reset the counts to 0!

If you wish to keep track of the previous month counts as well, use a List. When the month gets over, add the total amount to the array at the index of the month number. Also, keep in mind that the first index is 0, not 1. So, you'll have to offset the array by 1 value to be able to directly use the month number to query your list.

This has an advantage over R. Zagorski's idea (which is also quite good) that it can be used from api level 8 as that's the minimum for TrafficStats.

Hope I Helped :D



来源:https://stackoverflow.com/questions/40039874/how-to-get-the-gprs-mobile-data-usage-for-1-month

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