Android statistics on Wifi/2G/3G/4G traffic

Source: Internet
Author: User

Requirement: count the number of Wi-Fi/2G/3G/4G traffic


Issue:

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


Iii. Considerations

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.


Implementation Method:

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.





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.