How to get GPRS Mobile data usage in 1 month?

I searched a lot about this. Found the same code everywhere that partially solves the goal. As stated in the API documentation, it will reset the counter after restarting the device. Sometimes the counter is simply reset even without a reboot. 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 find a way to get this data from a specific date OR within a month? Please help. Any pointer would be appreciated. Thanks.

+5
source share
2 answers

First of all, TrafficStats.getTotalRxPackets () :

Returns the number of packets received since the device was booted.

The same thing happens with TrafficStats.getTotalTxPackets ()

This class will not help to get statistics for the month.

I would advise a solution to work with API 23:

NetworkStatsManager

This class has the ability to receive statistics for a device or package. The function is especially useful for you:

NetworkStatsManager.querySummaryForDevice ()

who expect measurement of the start time as the third parameter and the end time as the fourth parameter.

A sample project can be found here . It shows how to access NetworkStatsManager by requesting appropriate runtime permissions.

This solution is only API 23+.

If you really want to use TrafficStats , create a service that will get the result of TrafficStats.getTotalRxPackets () every hour, calculate the difference, save it in the database on a different line per day.

+4
source

I agree with R. Zagorsky, but I have a different approach.

Use TrafficStats to get the number 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 counter is greater than the current amount. If so, reset the last amount is 0. Also track when the month began. Once the month is over, remember to reset the count to 0!

If you want to track the invoice for the previous month, use the list. At the end of the month, 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. Thus, you will need to shift the array by 1 value in order to be able to directly use the month number to query your list.

This has an advantage over the idea of โ€‹โ€‹R. Zagorsky (which is also not bad) that it can be used from level 8 api at least for TrafficStats.

I hope I helped: D

0
source

Source: https://habr.com/ru/post/1258201/


All Articles