Current Download/Upload Speed in Android

1.8k Views Asked by At

All,

I am newbie in android, just developing app to display the current Download/Upload Speed. I have got some tips from this Example. It uses TrafficStats.getTotalRxBytes() function that returns the total Bytes received after boot and increases monotonically.

So i used the below code, to display only the Current Available Speed. But i am not getting the result. it displays the Total Tx/Rx values only.

  1. Is there any Alternative to achieve this? Any Code snippets would be much appreciated as i am a complete beginner.

  2. Also, i cant understand below code. Can some one explain this?

    private final Runnable mRunnable = new Runnable() 
    
  3. i need to refresh the data displayed in textView for every one second. I Guess

      mHandler.postDelayed(mRunnable, 1000) ( );   
    

    is used to do that. is there any alternative? if not, how does would be the control flow when using PostDelayed function? (I am bit confused)

    public class MainActivity extends Activity {
    
    private Handler mHandler = new Handler();
    private long mStartRX =0;
    private long mStartTX = 0;
    private static final int RESULT_SETTINGS = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler.postDelayed(mRunnable, 1000);
    
    }
    private final Runnable mRunnable = new Runnable() 
    {
    
          public void run() 
          {
    
            long TxResult=0;
            long RxResult=0;
            long or1=0,or2=0;
    
            long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX-or1; 
    
            if (rxBytes<1024)
            {
                RxResult=0;
    
            }
           else if (rxBytes>1024)
           {
               // RxResult=0;
               RxResult=RxResult+(rxBytes/1024);
           }
           TextView RX = (TextView)findViewById(R.id.rxOut);
           //mStartRX=rxBytes;
           TextView TX = (TextView)findViewById(R.id.txOut);
           RX.setText(Long.toString(RxResult));
           long txBytes = TrafficStats.getTotalTxBytes()- mStartTX-or2;
           if (txBytes<1024)
           {
               TxResult=0;
           }
           else if (txBytes>1024)
           {
               TxResult=0;
               TxResult=TxResult+(txBytes/1024);
           }
    
           TX.setText(Long.toString(TxResult));
           or2=or2+txBytes;
            or1=or1+rxBytes;
            mHandler.postDelayed(mRunnable, 100);
    
           }
     };
    
0

There are 0 best solutions below