将接收的字节转换为KB / MB - Android

时间:2015-02-15 14:23:19

标签: android

我使用下面的代码显示Transmitted和Receive字节:

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);  
        }
    }
}

但是我想为它添加单位(即KB,MB,GB)。例如,如果数据使用量小于1MB,则应以KB为单位显示,并且应分别更改为MB和GB。

2 个答案:

答案 0 :(得分:5)

使用此

 public static String getFileSize(long size) { 
    if (size <= 0)
     return "0";
     final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
     int digitGroups = (int) (Math.log10(size) / Math.log10(1024)); 
    return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
     }
}

答案 1 :(得分:0)

此代码适用于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

它假设totalRX是字节,并且设置文本为unit 然后更深入,并在满足大小(KB,MB,GB)时设置文本 如果它适合您,请使用相同的TX代码。

注意:如果您不喜欢多setText()次来电 您可以声明临时变量,sizeunit填充它们,因为您在if-statements之后更深入,setText()一次在主if-statement

之下
RX.setText(Long.toString(size) + " " + unit);