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.