Requirement: count the number of Wi-Fi/2G/3G/4G traffic
1. How to Determine 2G/3G/4G
The system source code TelephonyManager class provides methods, but only hidden, so you can refer to the source code
Ii. How to make statistics
The TrafficStats class is provided after Android 2.2 for traffic statistics. For more information, see the manual.
Here I used
Static long getTotalRxBytes () // obtain the total number of accepted bytes, including Mobile and WiFi.
Static long getTotalTxBytes () // The total number of sent bytes, including Mobile and WiFi
1. android.net. conn. CONNECTIVITY_CHANGE broadcast. the broadcast is sent when the network type of the mobile phone is switched.
2. the value obtained by the TrafficStats. getTotalRxBytes () and TrafficStats. getTotalTxBytes () methods is recorded from the start of the boot.
1. Create a TrafficData table with the following fields: trafficData (traffic used during network changes), subtype (network type), starttime (start time), and endtime (End Time)
2. Create Sharedpreferences, record lastSystemTraffic (Traffic Volume of the last system), subtype (network type), and startTime
3. register the rarafficreceiver. Listen to android.net. conn. CONNECTIVITY_CHANGE broadcast and shutdown broadcast. When the network changes, obtain
CurrentTraffic = TrafficStats. getTotalRxBytes () + TrafficStats. getTotalTxBytes (), read the lastSystemTraffic stored in the SP.
Last network traffic durationTraffic = currentTraffic-lastSystemTraffic. Save durationTraffic to data
And update the values in the SP.
4. When the phone restarts, repeat Step 3 and clear the values in the SP.