Android Stats WIFI/2G/3G/4G Traffic

Source: Internet
Author: User

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





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.