天天看點

android 流量的統計

1 android架構對流量的統計通過一個TrafficStats類可以直接擷取

    擷取總接受流量TrafficStats.getTotalRxBytes(),

    擷取總發送流量TrafficStats.getTotalTxBytes());

   擷取不包含WIFI的手機GPRS接收量TrafficStats.getMobileRxBytes());

   擷取不包含Wifi的手機GPRS發送量TrafficStats.getMobileTxBytes());

    統計某一個程序的總接收量TrafficStats.getUidRxBytes(Uid));

    統計某一個程序的總發送量TrafficStats.getUidTxBytes(Uid));

這些擷取的流量都是從一次開機到讀取時刻的統計量。

是以,統計某一個程式的流量統計的時候,一定要注意開關機,和本次開機後是第幾次啟動本程式。

2 android的TrafficStats類

前四個讀取的/proc/net/dev裡面的資料

後面的兩個接口對某一個程序的流量統計的是/proc/uid_stat/*** 接口裡面的節點 資料

package cn.sunzn.trafficmanger;

import android.app.Activity;

import android.net.TrafficStats;

import android.os.Bundle;

import android.view.Menu;

public class MainActivity extends Activity {

   public void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.activity_main);

       /** 擷取手機通過 2G/3G 接收的位元組流量總數 */

       TrafficStats.getMobileRxBytes();

       /** 擷取手機通過 2G/3G 接收的資料包總數 */

       TrafficStats.getMobileRxPackets();

       /** 擷取手機通過 2G/3G 發出的位元組流量總數 */

       TrafficStats.getMobileTxBytes();

       /** 擷取手機通過 2G/3G 發出的資料包總數 */

       TrafficStats.getMobileTxPackets();

       /** 擷取手機通過所有網絡方式接收的位元組流量總數(包括 wifi) */

       TrafficStats.getTotalRxBytes();

       /** 擷取手機通過所有網絡方式接收的資料包總數(包括 wifi) */

       TrafficStats.getTotalRxPackets();

       /** 擷取手機通過所有網絡方式發送的位元組流量總數(包括 wifi) */

       TrafficStats.getTotalTxBytes();

       /** 擷取手機通過所有網絡方式發送的資料包總數(包括 wifi) */

       TrafficStats.getTotalTxPackets();

       /** 擷取手機指定 UID 對應的應程式用通過所有網絡方式接收的位元組流量總數(包括 wifi) */

       TrafficStats.getUidRxBytes(uid);

       /** 擷取手機指定 UID 對應的應用程式通過所有網絡方式發送的位元組流量總數(包括 wifi) */

       TrafficStats.getUidTxBytes(uid);

   }

   public boolean onCreateOptionsMenu(Menu menu) {

       getMenuInflater().inflate(R.menu.activity_main, menu);

       return true;

}

Android OS下有幾個應用是集體的,包括(Android系統、設定存儲、設定、系統使用者界面、miui)

OS裡面的各個子產品的流量統計都算到OS 1000的流量,如果某一子產品出問題就不能夠揪出來,可以建立接口分别計算。