Android get network speed and download speed

Source: Internet
Author: User

Android get network speed and download speed


The display of network speed is often used in Android applications, especially when files are downloaded and videos are buffered. Today, I have encountered the need to display the network speed during video playback, using the TrafficStats class.

For more information, see the use of the TrafficStats class in Android traffic statistics.


Private void showNetSpeed () {long nowTotalRxBytes = getTotalRxBytes (); long nowTimeStamp = System. currentTimeMillis (); long speed = (response-interval) * 1000/(nowTimeStamp-lastTimeStamp); // millisecond conversion lastTimeStamp = nowTimeStamp; lastTotalRxBytes = bytes; Message msg = mHandler. obtainMessage (); msg. what = 100; msg. obj = String. valueOf (speed) + "kb/s"; mHandler. sendMessage (msg); // update interface}

The idea is to obtain Time periodObtained Network data sizeAnd then obtain the network speed value through calculation.

Private long lastTotalRxBytes = 0; private long lastTimeStamp = 0; private long getTotalRxBytes () {return TrafficStats. getUidRxBytes (getApplicationInfo (). uid) = TrafficStats. UNSUPPORTED? 0 :( TrafficStats. getTotalRxBytes ()/1024); // convert to KB} TimerTask task = new TimerTask () {@ Overridepublic void run () {showNetSpeed ();}};

Here, TimerTask is used to regularly obtain the network speed and send the message update interface.

Initialize data when starting a task

LastTotalRxBytes = getTotalRxBytes (); lastTimeStamp = System. currentTimeMillis (); new Timer (). schedule (task, 1000,200 0); // start the task once every 2 seconds


How often can I update and obtain the network speed as needed?


If you want to download multiple tasks and display the network speed separately, you can directly calculate the network speed by the data size downloaded within a certain interval. The method is similar.



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.