Android for speed and download speeds

Source: Internet
Author: User


The display of network speed is often used in Android applications, especially when downloading files and video buffers. Today I encountered the need to display the video playback speed, using the Trafficstats class.

Find information, reference the use of the Android traffic statistics Trafficstats class


private void Shownetspeed () {Long nowtotalrxbytes = Gettotalrxbytes (); Long nowtimestamp = System.currenttimemillis (); Long speed = ((nowtotalrxbytes-lasttotalrxbytes) * +/(Nowtimestamp-lasttimestamp));//MS Conversion Lasttimestamp = Nowtimes Tamp;lasttotalrxbytes = nowtotalrxbytes; Message msg = Mhandler.obtainmessage (), msg.what = 100;msg.obj = string.valueof (speed) + "kb/s"; Mhandler.sendmessage (msg );//Update interface}

The idea is to get the size of the network data from this time period every other time, and then calculate the speed value.

Private Long lasttotalrxbytes = 0;private long Lasttimestamp = 0;private long gettotalrxbytes () {return Trafficstats.getui Drxbytes (Getapplicationinfo (). uid) ==trafficstats.unsupported? 0:(Trafficstats.gettotalrxbytes ()/1024);//to Kb}timertask task = new TimerTask () {@Overridepublic void run () { Shownetspeed ();}};

here is the use of timertask to regularly get the speed, the concurrent message update interface.

When you start a task, the data is initialized

Lasttotalrxbytes = Gettotalrxbytes (); lasttimestamp = System.currenttimemillis (); new Timer (). Schedule (Task, 1000, 2000 ); 1s start task, execute once every 2s


Can be based on demand, how often update to get the speed


If you are downloading multiple tasks, you need to display the network speed separately, you can calculate the network speed directly by the size of the data downloaded at a certain time interval, similar method.



Android for speed and download speeds

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.