Exemplo n.º 1
0
  /** Begin monitoring connectivity */
  public void startMonitoring(Context context, Handler target) {
    mContext = context;
    mCsHandler = target;

    // register for notifications from NetworkManagement Service
    IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
    INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);

    mInterfaceObserver = new InterfaceObserver(this);

    // enable and try to connect to an ethernet interface that
    // already exists
    sIfaceMatch =
        context.getResources().getString(com.android.internal.R.string.config_ethernet_iface_regex);
    try {
      final String[] ifaces = service.listInterfaces();
      for (String iface : ifaces) {
        if (iface.matches(sIfaceMatch)) {
          mIface = iface;
          InterfaceConfiguration config = service.getInterfaceConfig(iface);
          mLinkUp = config.isActive();
          reconnect();
          break;
        }
      }
    } catch (RemoteException e) {
      Log.e(TAG, "Could not get list of interfaces " + e);
    }

    try {
      service.registerObserver(mInterfaceObserver);
    } catch (RemoteException e) {
      Log.e(TAG, "Could not register InterfaceObserver " + e);
    }
  }
 private void expectNetworkStatsPoll(String[] tetherIfacePairs, NetworkStats tetherStats)
     throws Exception {
   mNetManager.setGlobalAlert(anyLong());
   expectLastCall().anyTimes();
   expect(mConnManager.getTetheredIfacePairs()).andReturn(tetherIfacePairs).anyTimes();
   expect(mNetManager.getNetworkStatsTethering(eq(tetherIfacePairs)))
       .andReturn(tetherStats)
       .anyTimes();
 }
  private void expectSystemReady() throws Exception {
    mAlarmManager.remove(isA(PendingIntent.class));
    expectLastCall().anyTimes();

    mAlarmManager.setInexactRepeating(
        eq(AlarmManager.ELAPSED_REALTIME), anyLong(), anyLong(), isA(PendingIntent.class));
    expectLastCall().atLeastOnce();

    mNetManager.setGlobalAlert(anyLong());
    expectLastCall().atLeastOnce();
  }
 private void update(Set<Integer> users, Map<Integer, Boolean> apps, boolean add) {
   List<Integer> network = new ArrayList<Integer>();
   List<Integer> system = new ArrayList<Integer>();
   for (Entry<Integer, Boolean> app : apps.entrySet()) {
     List<Integer> list = app.getValue() ? system : network;
     for (int user : users) {
       list.add(UserHandle.getUid(user, app.getKey()));
     }
   }
   try {
     if (add) {
       mNetd.setPermission("NETWORK", toIntArray(network));
       mNetd.setPermission("SYSTEM", toIntArray(system));
     } else {
       mNetd.clearPermission(toIntArray(network));
       mNetd.clearPermission(toIntArray(system));
     }
   } catch (RemoteException e) {
     loge("Exception when updating permissions: " + e);
   }
 }
  @Override
  public void setUp() throws Exception {
    super.setUp();

    mServiceContext = new BroadcastInterceptingContext(getContext());
    mStatsDir = getContext().getFilesDir();
    if (mStatsDir.exists()) {
      IoUtils.deleteContents(mStatsDir);
    }

    mNetManager = createMock(INetworkManagementService.class);
    mAlarmManager = createMock(IAlarmManager.class);
    mTime = createMock(TrustedTime.class);
    mSettings = createMock(NetworkStatsSettings.class);
    mConnManager = createMock(IConnectivityManager.class);

    mService =
        new NetworkStatsService(
            mServiceContext, mNetManager, mAlarmManager, mTime, mStatsDir, mSettings);
    mService.bindConnectivityManager(mConnManager);

    mElapsedRealtime = 0L;

    expectCurrentTime();
    expectDefaultSettings();
    expectNetworkStatsSummary(buildEmptyStats());
    expectNetworkStatsUidDetail(buildEmptyStats());
    expectSystemReady();

    // catch INetworkManagementEventObserver during systemReady()
    final Capture<INetworkManagementEventObserver> networkObserver =
        new Capture<INetworkManagementEventObserver>();
    mNetManager.registerObserver(capture(networkObserver));
    expectLastCall().atLeastOnce();

    replay();
    mService.systemReady();
    verifyAndReset();

    mNetworkObserver = networkObserver.getValue();
  }
  private void updateHeaderList(List<Header> target) {
    final boolean showDev =
        mDevelopmentPreferences.getBoolean(
            DevelopmentSettings.PREF_SHOW,
            android.os.Build.TYPE.equals("eng") || android.os.Build.TYPE.equals("userdebug"));
    int i = 0;

    mHeaderIndexMap.clear();
    while (i < target.size()) {
      Header header = target.get(i);
      // Ids are integers, so downcasting
      int id = (int) header.id;
      if (id == R.id.operator_settings
          || id == R.id.manufacturer_settings
          || id == R.id.advanced_settings
          || id == R.id.hybrid_settings) {
        Utils.updateHeaderToSpecificActivityFromMetaDataOrRemove(this, target, header);
      } else if (id == R.id.launcher_settings) {
        Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
        launcherIntent.addCategory(Intent.CATEGORY_HOME);
        launcherIntent.addCategory(Intent.CATEGORY_DEFAULT);

        Intent launcherPreferencesIntent = new Intent(Intent.ACTION_MAIN);
        launcherPreferencesIntent.addCategory("com.cyanogenmod.category.LAUNCHER_PREFERENCES");

        ActivityInfo defaultLauncher =
            getPackageManager()
                .resolveActivity(launcherIntent, PackageManager.MATCH_DEFAULT_ONLY)
                .activityInfo;
        launcherPreferencesIntent.setPackage(defaultLauncher.packageName);
        ResolveInfo launcherPreferences =
            getPackageManager().resolveActivity(launcherPreferencesIntent, 0);
        if (launcherPreferences != null) {
          header.intent =
              new Intent()
                  .setClassName(
                      launcherPreferences.activityInfo.packageName,
                      launcherPreferences.activityInfo.name);
        } else {
          target.remove(header);
        }
      } else if (id == R.id.wifi_settings) {
        // Remove WiFi Settings if WiFi service is not available.
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI)) {
          target.remove(i);
        }
      } else if (id == R.id.bluetooth_settings) {
        // Remove Bluetooth Settings if Bluetooth service is not available.
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) {
          target.remove(i);
        }
      } else if (id == R.id.data_usage_settings) {
        // Remove data usage when kernel module not enabled
        final INetworkManagementService netManager =
            INetworkManagementService.Stub.asInterface(
                ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
        try {
          if (!netManager.isBandwidthControlEnabled()) {
            target.remove(i);
          }
        } catch (RemoteException e) {
          // ignored
        }
      } else if (id == R.id.account_settings) {
        int headerIndex = i + 1;
        i = insertAccountsHeaders(target, headerIndex);
      } else if (id == R.id.user_settings) {
        if (!UserHandle.MU_ENABLED
            || !UserManager.supportsMultipleUsers()
            || Utils.isMonkeyRunning()) {
          target.remove(i);
        }
      }

      if (target.get(i) == header
          && UserHandle.MU_ENABLED
          && UserHandle.myUserId() != 0
          && !ArrayUtils.contains(SETTINGS_FOR_RESTRICTED, id)) {
        target.remove(i);
      }

      // Increment if the current one wasn't removed by the Utils code.
      if (target.get(i) == header) {
        // Hold on to the first header, when we need to reset to the top-level
        if (mFirstHeader == null
            && HeaderAdapter.getHeaderType(header) != HeaderAdapter.HEADER_TYPE_CATEGORY) {
          mFirstHeader = header;
        }
        mHeaderIndexMap.put(id, i);
        i++;
      }
    }
  }
 private void expectNetworkStatsUidDetail(NetworkStats detail) throws Exception {
   expect(mNetManager.getNetworkStatsUidDetail(eq(UID_ALL))).andReturn(detail).atLeastOnce();
 }
 private void expectNetworkStatsSummary(NetworkStats summary) throws Exception {
   expect(mNetManager.getNetworkStatsSummary()).andReturn(summary).atLeastOnce();
 }
  public void testStatsRebootPersist() throws Exception {
    assertStatsFilesExist(false);

    // pretend that wifi network comes online; service should ask about full
    // network state, and poll any existing interfaces before updating.
    expectCurrentTime();
    expectDefaultSettings();
    expectNetworkState(buildWifiState());
    expectNetworkStatsSummary(buildEmptyStats());
    expectNetworkStatsUidDetail(buildEmptyStats());
    expectNetworkStatsPoll();

    replay();
    mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION_IMMEDIATE));

    // verify service has empty history for wifi
    assertNetworkTotal(sTemplateWifi, 0L, 0L, 0L, 0L, 0);
    verifyAndReset();

    // modify some number on wifi, and trigger poll event
    incrementCurrentTime(HOUR_IN_MILLIS);
    expectCurrentTime();
    expectDefaultSettings();
    expectNetworkStatsSummary(
        new NetworkStats(getElapsedRealtime(), 1)
            .addIfaceValues(TEST_IFACE, 1024L, 8L, 2048L, 16L));
    expectNetworkStatsUidDetail(
        new NetworkStats(getElapsedRealtime(), 2)
            .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 512L, 4L, 256L, 2L, 0L)
            .addValues(TEST_IFACE, UID_RED, SET_DEFAULT, 0xFAAD, 256L, 2L, 128L, 1L, 0L)
            .addValues(TEST_IFACE, UID_RED, SET_FOREGROUND, TAG_NONE, 512L, 4L, 256L, 2L, 0L)
            .addValues(TEST_IFACE, UID_RED, SET_FOREGROUND, 0xFAAD, 256L, 2L, 128L, 1L, 0L)
            .addValues(TEST_IFACE, UID_BLUE, SET_DEFAULT, TAG_NONE, 128L, 1L, 128L, 1L, 0L));
    expectNetworkStatsPoll();

    mService.setUidForeground(UID_RED, false);
    mService.incrementOperationCount(UID_RED, 0xFAAD, 4);
    mService.setUidForeground(UID_RED, true);
    mService.incrementOperationCount(UID_RED, 0xFAAD, 6);

    replay();
    mServiceContext.sendBroadcast(new Intent(ACTION_NETWORK_STATS_POLL));

    // verify service recorded history
    assertNetworkTotal(sTemplateWifi, 1024L, 8L, 2048L, 16L, 0);
    assertUidTotal(sTemplateWifi, UID_RED, 1024L, 8L, 512L, 4L, 10);
    assertUidTotal(sTemplateWifi, UID_RED, SET_DEFAULT, 512L, 4L, 256L, 2L, 4);
    assertUidTotal(sTemplateWifi, UID_RED, SET_FOREGROUND, 512L, 4L, 256L, 2L, 6);
    assertUidTotal(sTemplateWifi, UID_BLUE, 128L, 1L, 128L, 1L, 0);
    verifyAndReset();

    // graceful shutdown system, which should trigger persist of stats, and
    // clear any values in memory.
    expectCurrentTime();
    expectDefaultSettings();
    replay();
    mServiceContext.sendBroadcast(new Intent(Intent.ACTION_SHUTDOWN));
    verifyAndReset();

    // talk with zombie service to assert stats have gone; and assert that
    // we persisted them to file.
    expectDefaultSettings();
    replay();
    assertNetworkTotal(sTemplateWifi, 0L, 0L, 0L, 0L, 0);
    verifyAndReset();

    assertStatsFilesExist(true);

    // boot through serviceReady() again
    expectCurrentTime();
    expectDefaultSettings();
    expectNetworkStatsSummary(buildEmptyStats());
    expectNetworkStatsUidDetail(buildEmptyStats());
    expectSystemReady();

    // catch INetworkManagementEventObserver during systemReady()
    final Capture<INetworkManagementEventObserver> networkObserver =
        new Capture<INetworkManagementEventObserver>();
    mNetManager.registerObserver(capture(networkObserver));
    expectLastCall().atLeastOnce();

    replay();
    mService.systemReady();

    mNetworkObserver = networkObserver.getValue();

    // after systemReady(), we should have historical stats loaded again
    assertNetworkTotal(sTemplateWifi, 1024L, 8L, 2048L, 16L, 0);
    assertUidTotal(sTemplateWifi, UID_RED, 1024L, 8L, 512L, 4L, 10);
    assertUidTotal(sTemplateWifi, UID_RED, SET_DEFAULT, 512L, 4L, 256L, 2L, 4);
    assertUidTotal(sTemplateWifi, UID_RED, SET_FOREGROUND, 512L, 4L, 256L, 2L, 6);
    assertUidTotal(sTemplateWifi, UID_BLUE, 128L, 1L, 128L, 1L, 0);
    verifyAndReset();
  }