问题
I want to calculate the amount of network usage/network traffic stats for my app in a month.
I can use TrafficStats to provides network traffic statistics, but the statistics returned by this class reset and start from zero after every reboot. I think about storing the statistics on the storage, but I want another way.
So I change to use NetworkStatsManager to calculate, but most of method required API >= 23.
So how can I do it with api below 23? Thank you.
回答1:
you should persist the data from traffic stat in sqlite
at some time interval. And store the last reading just before Shutdown using
action android.intent.action.ACTION_SHUTDOWN
in broadcastreceiver. After restart, you should start storing the data again. This way, you will not lost the data. The solution works on all android version.
回答2:
I can use TrafficStats to provides network traffic statistics, but the statistics returned by this class reset and start from zero after every reboot.
How about storing this data somewhere? E.g. in SharedPreferences, SQLite database or somewhere else. After that, your data will be persisted after reboot and you can accumulate the calculated results.
回答3:
Even if we persist the data in sqlite, it is not necessary that the value is reset to zero after shut down of device. In that case there is confusion whether to add the previous stored bytes with the value that we get after reset, because the value is not always zero after shut down.
来源:https://stackoverflow.com/questions/49107929/calculate-network-traffic-stats-of-app-during-a-month