天天看點

擷取程序流量資訊

知識點:

擷取包名

擷取UID

TrafficStats 類

public class ScreenSaverTask extends Thread {

  private int uid;
  private ApplicationTest application;
  private final String TAG = "ScreenSaverTask";

  public ScreenSaverTask(ApplicationTest application) {
    this.application = application;
    // uid = getUid();
    uid = 0;
    d(TAG, "ScreenSaverTask create!");
  }

  @Override
  public void run() {
    super.run();
    d(TAG, "ScreenSaverTask start!");
    while (true) {
      try {
        sleep(1000);

        d(TAG, "uid: " + uid + "RxBytes: " + getRxBytes(uid));
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

    }
  }

  public int getUid() {

    try {

      PackageManager pm = application.getPackageManager();
      ApplicationInfo ai = pm
          .getApplicationInfo(application.getPackageName(),
              PackageManager.GET_ACTIVITIES);
      Log.d(TAG, "UID: " + ai.uid);

      return ai.uid;
    } catch (Exception e) {
      e.printStackTrace();
    }

    return -1;
  }

  public long getRxBytes(int uid) {

    return TrafficStats.getUidRxBytes(uid);
  }

  public void d(String TAG, String content) {
    Log.d(TAG, "--- " + content + " ---");
  }

}