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