Trafficstats-an example of the traffic statistics class to get the real-time network speed

Source: Internet
Author: User
Tags netspeed

 

 

Android provided this type of API at the beginning of 2.3, so that we can conveniently use it to calculate mobile phone traffic. This class is actually very simple. I have pasted several of his methods and you will know how to use them at a glance.

Static long getmobilerxbytes () // gets the total number of bytes received through mobile connections, excluding WiFi
Static long getmobilerxpackets () // gets the total number of packets received by the mobile connection.
Static long getmobiletxbytes () // total number of bytes sent by mobile
Static long getmobiletxpackets () // total number of data packets sent by mobile
Static long gettotalrxbytes () // obtain the total number of accepted bytes, including mobile and WiFi.
Static long gettotalrxpackets () // total number of accepted packets, including mobile and WiFi
Static long gettotaltxbytes () // The total number of sent bytes, including mobile and WiFi
Static long gettotaltxpackets () // total number of data packets sent, including mobile and WiFi
Static long getuidrxbytes (int uid) // gets the number of bytes that a network uid receives and the total number of bytes that a process receives.
Static long getuidtxbytes (int uid) // gets the number of bytes sent by a network UID and the total number of bytes sent by a process.

 

The following describes how to implement real-time network speed:

1. Get the current total accepted data, gettotalrxpackets ()

2. Obtain the total received data every several seconds.

3. About the latest acquired data minus the previously obtained data and divided by the interval seconds, the average network speed of B/S is obtained, and the Unit is converted to kb, MB, and so on.

 

Implementation:

1. Obtain the current network speed

Initially, a value is given to total_data:

private long total_data = TrafficStats.getTotalRxBytes();

Then, the value obtained each time is subtracted from total_data and then divided by the number of seconds, and total is assigned to the latest value.

/*** Core method to obtain the current network speed * @ return */private int getnetspeed () {long traffic_data = trafficstats. gettotalrxbytes ()-total_data; total_data = trafficstats. gettotalrxbytes (); Return (INT) traffic_data/count ;}

 

2. periodically obtain the network speed

/*** Define the thread to get the network speed cyclically */private runnable mrunnable = new runnable () {@ override public void run () {// timer mhandler. postdelayed (mrunnable, count * 1000); message MSG = mhandler. obtainmessage (); MSG. what = 1; MSG. arg1 = getnetspeed (); mhandler. sendmessage (MSG );}};

 

3. unit conversion

@Override    public void onCreate() {        super.onCreate();                mHandler = new Handler(){            @Override            public void handleMessage(Message msg) {                super.handleMessage(msg);                if (msg.what == 1) {                    //float real_data = (float)msg.arg1;                    if(msg.arg1  > 1024 ){                        System.out.println(msg.arg1 / 1024 + "kb/s");                                        }                    else{                        System.out.println(msg.arg1 + "b/s");                        }                }            }        };    }

 

4. Start and Stop Handler

PS: when the service starts, the method in runnable is executed, and the handler loop is set in runnable. When running the run () method in runnable, package the network speed to the message and hand it to the handler for unit conversion and display (here in handler for unit conversion to facilitate display to the UI)

/*** Start the thread to get the network speed */@ override public void onstart (intent, int startid) {mhandler. postdelayed (mrunnable, 0) ;};/*** Delete the message queue at the end of the service */@ override public void ondestroy () {mhandler. removecallbacks (mrunnable); super. ondestroy ();};

 

@Override    public void onCreate() {        super.onCreate();                mHandler = new Handler(){            @Override            public void handleMessage(Message msg) {                super.handleMessage(msg);                if (msg.what == 1) {                    //float real_data = (float)msg.arg1;                    if(msg.arg1  > 1024 ){                        System.out.println(msg.arg1 / 1024 + "kb/s");                                        }                    else{                        System.out.println(msg.arg1 + "b/s");                        }                }            }        };

 

Finally, all code

Service:

Package COM. kale. netspeed; import android. app. service; import android. content. intent; import android.net. trafficstats; import android. OS. handler; import android. OS. ibinder; import android. OS. message;/*** @ Author: Jack Tony * @ tips: obtains the service of the current network speed in real time * @ Date: 2014-9-24 */public class net_service extends Service {private long total_data = trafficstats. gettotalrxbytes (); Private handler mhandler; // refresh private final int COUNT = 5 in seconds; /*** define the thread to get the network speed cyclically */private runnable mrunnable = new runnable () {@ override public void run () {// timer mhandler. postdelayed (mrunnable, count * 1000); message MSG = mhandler. obtainmessage (); MSG. what = 1; MSG. arg1 = getnetspeed (); mhandler. sendmessage (MSG) ;};@ override public void oncreate () {super. oncreate (); mhandler = new handler () {@ override public void handlemessage (Message MSG) {super. handlemessage (MSG); If (MSG. what = 1) {// float real_data = (float) MSG. arg1; If (MSG. armg1> 1024) {system. out. println (MSG. arg1/1024 + "kb/s");} else {system. out. println (MSG. arg1 + "B/S") ;}}};}/ *** core method to obtain the current network speed * @ return */private int getnetspeed () {long traffic_data = trafficstats. gettotalrxbytes ()-total_data; total_data = trafficstats. gettotalrxbytes (); Return (INT) traffic_data/count;}/*** start the thread to get the network speed when starting the Service */@ override public void onstart (intent, int startid) {mhandler. postdelayed (mrunnable, 0) ;};/*** Delete the message queue at the end of the service */@ override public void ondestroy () {mhandler. removecallbacks (mrunnable); super. ondestroy () ;};@ override public ibinder onbind (intent) {return NULL ;}}

 

<service android:name="com.kale.netspeed.Net_Service"/>

 

Activity:

package com.kale.netspeed;import android.app.Activity;import android.content.Intent;import android.os.Bundle;public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                startService(new Intent(MainActivity.this,Net_Service.class));    }}

 

Reference: http://gundumw100.iteye.com/blog/1294167

 

Trafficstats-an example of the traffic statistics class to get the real-time network speed

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.