Android设备网络数据流量统计

统计自设备启动以来的流量。

        JSONObject jsonObject = new JSONObject();

        //获取通过Mobile连接收到的字节总数,但不包含WiFi。
        long mobileRxBytes = TrafficStats.getMobileRxBytes();
        jsonObject.put("mobileRxBytes", mobileRxBytes);

        //获取Mobile连接收到的数据包总数。
        long mobileRxPackets = TrafficStats.getMobileRxPackets();
        jsonObject.put("mobileRxPackets", mobileRxPackets);

        //Mobile发送的总字节数。
        long mobileTxBytes = TrafficStats.getMobileTxBytes();
        jsonObject.put("mobileTxBytes", mobileTxBytes);

        //Mobile发送的总数据包数。
        long mobileTxPackets = TrafficStats.getMobileTxPackets();
        jsonObject.put("mobileTxPackets", mobileTxPackets);

        //获取总的接受字节数,包含Mobile和WiFi等。
        long totalRxBytes = TrafficStats.getTotalRxBytes();
        jsonObject.put("totalRxBytes", totalRxBytes);

        //总的接受数据包数,包含Mobile和WiFi等。
        long totalRxPackets = TrafficStats.getTotalRxPackets();
        jsonObject.put("totalRxPackets", totalRxPackets);

        //总的发送字节数,包含Mobile和WiFi等。
        long totalTxBytes = TrafficStats.getTotalTxBytes();
        jsonObject.put("totalTxBytes", totalTxBytes);

        //发送的总数据包数,包含Mobile和WiFi等。
        long totalTxPackets = TrafficStats.getTotalTxPackets();
        jsonObject.put("totalTxPackets", totalTxPackets);

        return jsonObject;

利用上面代码,可以每隔一段时间(如1秒,3秒),轮询一次,然后和上一次的结果做减法,就可以做出该设备的流量统计。

输出:

{"mobileRxBytes":0,"mobileRxPackets":0,"mobileTxBytes":0,"mobileTxPackets":0,"totalRxBytes":11776793541,"totalRxPackets":12722876,"totalTxBytes":2400919658,"totalTxPackets":7667607}

 

 

你可能感兴趣的:(Android)