Requirements: Statistics wifi/2g/3g/4g flow of how many
Issue:
I. How to Judge 2G/3G/4G
System source Telephonymanager class to provide a method, just hidden, so you can reference the source code
Two. How to Count
Android 2.2 provides trafficstats class for traffic statistics, using reference manuals
I used it here.
Static long Gettotalrxbytes ()//Gets the total number of bytes accepted, including mobile and WiFi, etc.
Static long Gettotaltxbytes ()//Total number of bytes sent, including mobile and WiFi, etc.
Three. Precautions
1. Android.net.conn.CONNECTIVITY_CHANGE broadcast, when the mobile network type switch, the system will send this broadcast
2. The values obtained by the trafficstats.gettotalrxbytes () and Trafficstats.gettotaltxbytes () methods are recorded from the start of the boot
Implementation method:
1. Create Trafficdata table, field trafficdata (how much traffic is used for network changes), subtype (network type), StartTime (Start time), Endtime (end time)
2. Create Sharedpreferences, Record lastsystemtraffic (last system's traffic size), subtype (network type), StartTime
3. Register Datatrafficreceiver. Monitor Android.net.conn.CONNECTIVITY_CHANGE broadcast and shutdown broadcast, when the network changes, get
Currenttraffic=trafficstats.gettotalrxbytes () +trafficstats.gettotaltxbytes (), reads the lastsystemtraffic saved in the SP.
Last network usage traffic durationtraffic=currenttraffic-lastsystemtraffic. Save the durationtraffic in the data
and update the values in the SP
4. Repeat 3 steps when the phone restarts, and empty the values in the SP