如何使用 TrafficStats 分别统计 2G 和 3G 的数据使用量?

How to count separately data usage in 2G and 3G with TrafficStats?

当phone是2G或3G时,如何mix/join以下两段代码分别统计TX和RX字节数?

我有以下代码来识别 phone 何时连接到似乎有效的 EDGE 或 UMTS 网络,并在显示屏上显示 Toast 消息。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        PhoneStateListener ConnectionStateListener = new PhoneStateListener() {

            @Override
            public void onDataConnectionStateChanged(int state, int networkType) {
                super.onDataConnectionStateChanged(state, networkType);
                String sState = "";

                switch (networkType) {
                    case TelephonyManager.NETWORK_TYPE_EDGE:   sState = "EDGE (2G)";   break;
                    case TelephonyManager.NETWORK_TYPE_UMTS:   sState = "UMTS (3G)";   break;                    
                }
                Toast.makeText(getApplicationContext(), sState, Toast.LENGTH_SHORT).show();
            }
        };
        telephonyManager.listen(ConnectionStateListener,PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
    }
}

Tech Republic 中的这个示例中,我得到了这段代码来计算 TX 和 RX 字节。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mStartRX = TrafficStats.getTotalRxBytes();
        mStartTX = TrafficStats.getTotalTxBytes();

        mHandler.postDelayed(mRunnable, 1000);
    }

    //This would be to update the bytes usage every second
    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);
        }
        };
}

也许有人可以帮我解决这个问题。提前感谢任何 advice/help.

如果我觉得你的问题有误,请纠正我。

您想分别统计 2G 和 3G 数据的 TX 和 RX。

将必要的代码复制到单个 activity。

取一个布尔值 is3G 并更改它 onDataConnectionStateChanged

然后触发mRunnable

telephonyManager.listen(ConnectionStateListener,PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);

mHandler.postDelayed(mRunnable, 1000);

mRunnable

中为2G和3G分别测量rx/tx字节
 if(is3G) {
      rxBytes3G = TrafficStats.getTotalRxBytes() - mStartRX - rxBytes2G;
      txBytes3G = TrafficStats.getTotalTxBytes() - mStartTX - txBytes2G;
  } else {
      rxBytes2G = TrafficStats.getTotalRxBytes() - mStartRX - rxBytes3G;
      txBytes2G  = TrafficStats.getTotalTxBytes() - mStartTX - txBytes3G;
  }

更新您的 ui