Android流量监控

jopen 12年前

1、TrafficStats类的使用

以下结论,是自己真机实测的结果,与自己在网上看到的不同,大家可自测验证。

(1)getMobile...方法,获取Gprs/3G流量

(2)getTotal...方法,获取Gprs/3G+Wifi的流量

以上两类方法统计的都是,从打开网络开始,到关闭网络,这一段时间内使用的流量。例如:10点打开,11点关闭,那么getMobileRxBytes方法,回返的是这段时间内Gprs/3G接受到的字节数。

(3)getUid...方法,获取某个网络UID的流量。这类方法,返回的是,从开机到关机,某个网络UID(我理解就是某个应用,如果不对,请在评论中指正)使用的Gprs/3G+Wifi的流量

 

2、getUid...方法的使用

    List<PackageInfo> packinfos = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_PERMISSIONS);        for (PackageInfo info : packinfos) {            String[] premissions = info.requestedPermissions;            if (premissions != null && premissions.length > 0) {                for (String premission : premissions) {                    if ("android.permission.INTERNET".equals(premission)) {                        // System.out.println(info.packageName+"访问网络");                        int uid = info.applicationInfo.uid;                        long rx = TrafficStats.getUidRxBytes(uid);                        long tx = TrafficStats.getUidTxBytes(uid);                        if (rx < 0 || tx < 0) {                            System.out.println(info.packageName + "没有产生流量");                        } else {                            System.out.println(info.packageName + "的流量信息:");                            System.out.println("下载的流量" + Formatter.formatFileSize(this, rx));                            System.out.println("上传的流量" + Formatter.formatFileSize(this, tx));                        }                    }                }                System.out.println("---------");            }        }  
3、获取流量信息的Service类

(1)因为两个广播都需要动态注册,所以写成了Service

(2)getMobile...和getTotal...方法获取的都是从打开网络开始,到关闭网络,这一段时间内使用的流量。

因此要在网络正在关闭时获取的就是这段时间的流量,WifiManager.WIFI_STATE_DISABLING表示的就是这个状态

(3)Gprs/3G貌似没有类似的状态,可以被监控到,只有,State.CONNECTED和State.DISCONNECTED。但是处于State.DISCONNECTED这个状态时,getMobile...方法获取到的值就都是0了

所有,我不得不在State.CONNECTED这个状态开始时,开启线程用于获取Gprs/3G的流量,直到我获取的到数据为0时,保存上一次的数据。

package forrest.forassist.service;    import android.app.Service;  import android.content.BroadcastReceiver;  import android.content.Context;  import android.content.Intent;  import android.content.IntentFilter;  import android.net.ConnectivityManager;  import android.net.NetworkInfo;  import android.net.NetworkInfo.State;  import android.net.TrafficStats;  import android.net.wifi.WifiManager;  import android.os.IBinder;  import android.text.format.Formatter;  import android.util.Log;  import forrest.forassist.db.MySQLiteDatabase;  import forrest.forassist.utils.Util;    public class TrafficService extends Service {     private TrafficReceiver tReceiver;   private WifiManager wifiManager;   private ConnectivityManager cManager;     public IBinder onBind(Intent intent) {    return null;   }     public void onCreate() {    // WifiManager,ConnectivityManager    wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);    cManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);    // 注册TrafficReceiver    tReceiver = new TrafficReceiver();    IntentFilter filter = new IntentFilter();    filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);    registerReceiver(tReceiver, filter);    super.onCreate();   }     public int onStartCommand(Intent intent, int flags, int startId) {      return super.onStartCommand(intent, flags, startId);   }     private class TrafficReceiver extends BroadcastReceiver {    private String action = "";    private static final String TAG = "TrafficReceiver";    long mobileRx;    long mobileTx;      public void onReceive(Context context, Intent intent) {     action = intent.getAction();     if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {      if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLING) {       Log.i(TAG, "WIFI_STATE_DISABLING");       long wifiDown = TrafficStats.getTotalRxBytes() - TrafficStats.getMobileRxBytes();       long wifiUp = TrafficStats.getTotalTxBytes() - TrafficStats.getMobileTxBytes();       MySQLiteDatabase sqLite = new MySQLiteDatabase(context); // 打开数据库       sqLite.insertWifi(Util.todayDate, wifiDown, wifiUp);       sqLite.closeDB();       Log.i(TAG, "wifi下载流量" + Formatter.formatFileSize(context, wifiDown));       Log.i(TAG, "wifi上传流量" + Formatter.formatFileSize(context, wifiUp));      }     } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {      Log.i(TAG, "CONNECTIVITY_ACTION");      NetworkInfo networkInfo = cManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);      State state = networkInfo.getState();      if (state == State.CONNECTED) {       Log.i(TAG, "State.CONNECTED");       // 开始不断获取最近的流量信息,值为0时,跳过       new Thread() {        public void run() {         long mobileRxType = TrafficStats.getMobileRxBytes();         long mobileTxType = TrafficStats.getMobileTxBytes();         if (mobileRxType + mobileTxType != 0) {          try {           mobileRx = mobileRxType;           mobileTx = mobileTxType;           Log.i(TAG, "mobileRx:" + mobileRx);           Log.i(TAG, "mobileTx:" + mobileTx);           Thread.sleep(1000);           run();          } catch (InterruptedException e) {           e.printStackTrace();          }         } else {          // 写入数据库          Log.i(TAG, "写入数据库");          MySQLiteDatabase sqLite = new MySQLiteDatabase(TrafficService.this);          sqLite.insertGprs(Util.todayDate, mobileRx, mobileTx);          sqLite.closeDB();         }        };       }.start();      }      }    }   }     public void onDestroy() {    unregisterReceiver(tReceiver);    super.onDestroy();   }  }