Below is the class which returns me data counter value in String. I was wanted to format String into KB, MB, and GB
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView infoView = (TextView)findViewById(R.id.traffic_info);
String info = "";
long getmobilerxbytes = TrafficStats.getMobileRxBytes();
long getmobilerxpackets = TrafficStats.getMobileRxPackets();
long getmobiletxbytes = TrafficStats.getMobileTxBytes();
long getmobiletxpackets = TrafficStats.getMobileTxPackets();
long totalrxbytes = TrafficStats.getTotalRxBytes();
long totalrxpackets = TrafficStats.getTotalRxPackets();
long totaltxbytes = TrafficStats.getTotalTxBytes();
long totaltxpackets = TrafficStats.getTotalTxPackets();
info += "Mobile Interface:\n";
info += ("\tReceived: " + getmobilerxbytes + " bytes / " + getmobilerxpackets + " packets\n");
info += ("\tTransmitted: " + getmobiletxbytes + " bytes / " + getmobiletxpackets + " packets\n");
info += "All Network Interface:\n";
info += ("\tReceived: " + totalrxbytes + " bytes / " + totalrxpackets + " packets\n");
info += ("\tTransmitted: " + totaltxbytes + " bytes / " + totaltxpackets + " packets\n");
infoView.setText(info);
}
Here is beautiful method to do that :
public static String humanReadableByteCount(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
But I am not sure how can i use above method in my onCreate code
Thanks in advance