First, understand the api provided by android for traffic statistics.
For Android traffic statistics, you can easily obtain the TrafficStats class added to Version 2.2. In fact, the TrafficStats class also reads the text of the file object system type provided by Linux for parsing.
If you are interested, you can read the source code of this class.
In the android.net. TrafficStats class, multiple static methods are provided, which can be directly called for retrieval. The return type is long. If the return value is-1, the current device does not support statistics.
1. static long getMobileRxBytes () // gets the total number of bytes received through the Mobile connection, excluding WiFi
2. static long getMobileRxPackets () // gets the total number of packets received by the Mobile connection, excluding WiFi
3. static long getMobileTxBytes () // The total number of bytes sent by Mobile
4. static long getMobileTxPackets () // total number of data packets sent by Mobile
5. static long getTotalRxBytes () // obtain the total number of accepted bytes, including Mobile and WiFi.
6. static long getTotalRxPackets () // total number of accepted packets, including Mobile and WiFi
7. static long getTotalTxBytes () // The total number of sent bytes, including Mobile and WiFi
8. static long getTotalTxPackets () // total number of data packets sent, including Mobile and WiFi
9. static long getUidRxBytes (int uid) // obtain the number of bytes accepted by a network UID
10. static long getUidTxBytes (int uid) // obtain the number of bytes sent by a network UID
Finally, we reminded you that the TrafficStats class works on the firmware with the Android 2.2 API Level of 8. If you want to support systems below Android 8, refer to TrafficStats source code.
The data is from the start of the current Boot and the traffic to the query time. After the shutdown, the data will be cleared.
How to Design:
Because each boot is different, you need to set a broadcast receiver to receive the boot and shutdown broadcasts and decide the initialization and storage of traffic. Of course, you also need to query and save the data each time you view the traffic, and save the statistical data to the database.
How to design a database?
A data table record: the value of each query, the query time, network type, network traffic, and whether it is the marker for saving when shutdown.
Total traffic for each query = current traffic + traffic for all shutdown and storage, you can also enable a service after the program is started, which does not last long. You can also save the job at every night. Note that getUidRxBytes (int uid) can only retrieve all data, including 2g/3g and Wi-Fi.
Author: dylove98