Issue
I use the below code to display Transmitted and received bytes:
public class MainActivity extends Activity {
private Handler mHandler = new Handler();
private long mStartRX = 0;
private long mStartTX = 0;
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView) findViewById(R.id.RX);
TextView TX = (TextView) findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes() - mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes() - mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED
|| mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}
}
}
But I want to add units to it (i.e KB, MB, GB). For example, if the data usage is less than 1MB, it should display in KB and should change to MB and GB respectively.
Solution
this code should work for RX:
long rxBytes = TrafficStats.getTotalRxBytes() - mStartRX;
RX.setText(Long.toString(rxBytes) + " bytes");
if(rxBytes>=1024){
//KB or more
long rxKb = rxBytes/1024;
RX.setText(Long.toString(rxKb) + " KBs");
if(rxKb>=1024){
//MB or more
long rxMB = rxKb/1024;
RX.setText(Long.toString(rxMB) + " MBs");
if(rxMB>=1024){
//GB or more
long rxGB = rxMB/1024;
RX.setText(Long.toString(rxGB));
}//rxMB>1024
}//rxKb > 1024
}//rxBytes>=1024
it assumes that totalRX is bytes, and set's text with unit then goes deeper, and set text if size fulfilled (KB, MB, GB) if it worked for you, use the same code for TX.
Note: if you don't like the multi setText()
calls
you can declare temp variables, for size
and unit
fill them as you go deeper in the if-statements
then setText()
one time below main if-statement
RX.setText(Long.toString(size) + " " + unit);
Answered By - Yazan
Answer Checked By - David Marino (JavaFixing Volunteer)